名前にスペースが含まれているディレクトリを繰り返します。

名前にスペースが含まれているディレクトリを繰り返します。

ディレクトリを繰り返し、ディレクトリ名と一致するようにサブディレクトリのファイル名を変更するスクリプトを作成しようとしています。ディレクトリ名にスペースが含まれていると、名前が分割され、必要に応じて何もできないという問題があります。

たとえば、フォルダ構造は次のようになります。

TopLevel
->this is a test
-->test.txt

これまで私のスクリプトは次のようになります

#!/bin/sh
topLevel="/dir1/dir2/TopLevel"
for dir in $(ls $topLevel)
do
    echo $dir # for testing purposes to make sure i'm getting the right thing
    # Get name of directory - i know how to do this
    # Rename file to match the name of the directory, with the existing extension - i know how to do this
done

私の予想結果は

/dir1/dir2/TopLevel/this is a test

しかし、実際の出力は

this
is
a
test

誰もが正しい方向に私を指すことができますか?久しぶりにシェルスクリプトをしてみました。このスクリプトを一度に1つずつ完了しようとしていますが、繰り返しを完了するのをやめたようです。

ベストアンサー1

これがこれを行う必要がある主な理由の1つです。出力を解析しないでください。ls。シェルグローブのみを使用している場合は、次のことができます。

for dir in /dir1/dir2/TopLevel/*/
do
    echo "$dir" ## note the quotes, those are essential
done

コメント

  • for dir in /dir1/dir2/TopLevel/*/単にディレクトリを繰り返すのではなく、私がどのように使用しているのかに注意してくださいfor dir in /dir1/dir2/TopLevel/*。ディレクトリとファイルが必要な場合for f in /dir1/dir2/TopLevel/*

  • 二重引用符は$dir必須であり、特に変数にスペースが含まれている場合は常に変数を引用符で囲む必要があります。

追加資料:

おすすめ記事