部分ディレクトリ名に基づいて複数のディレクトリのファイル名を変更する

部分ディレクトリ名に基づいて複数のディレクトリのファイル名を変更する

ある場所にさまざまな拡張子を持つファイルを含む複数のディレクトリがあります。これらのディレクトリは標準の規則に従いますが、その中にあるファイルはそうではありません。私が見つけようとしている解決策は、各フォルダ内のファイルの名前をそのファイルがあるディレクトリの部分に応じて変更して、検索する必要があるフォルダのリストを取得することです。

例えば:

ディレクトリ: 001234@Redsox#17

file1.pdf
file7A.doc
spreadsheet.xls

出力:

[email protected]
[email protected]
[email protected]

各ディレクトリに対してフォローアップを行い、ディレクトリ名に追加されたコードのみを名前変更します。全体的なプロセス作業のための基本的なフレームワークはすでにありますが、必要なディレクトリ部分を取得する最善の方法がわかりません。

for directory in *; do 
    pushd "$directory"
    index=1
    for filename in *; do
        target_filename="${directory}$????${filename}"
        mv "$filename" "${target_filename}"
        ((index++))
   done
  popd
done

ベストアンサー1

私は次のようにします:

# nullglob
#    If set, Bash allows filename patterns which match no files to
# expand to a null string, rather than themselves.
shopt -s nullglob

# instead of looping through the dirs, loop through the files
# add al the possible extensions in the list
$ for f in */*.{doc,pdf,xls,txt}; do 
  # get the file dirname
  d=$(dirname "$f")
                  # using parameter expansion get the part
                  # of the dirname you need
  echo mv -- "$f" "$d/${d%%@*}@$(basename "$f")"

  # when you are satisfied with the result, remove the `echo`
done
$ ls -1 001234@Redsox#17/
[email protected]
[email protected]
[email protected]

おすすめ記事