フォルダ名に特殊文字を追加する

フォルダ名に特殊文字を追加する

次の命名規則に従う長いフォルダのリストがあります。

ABS1789_2563-01
ABS1789_2563-02
ABS1789_2563-02

.
.
.

bashを使用してABSと1789の間に「-」を追加してから、1789と2563の間に「_」を「-」に変更するにはどうすればよいですか?

ベストアンサー1

IFS="\n"                        # Handle files with spaces in the names
for file in ABS*; do
    newfile="${file/ABS/ABS-}"  # Add the hyphen following ABS
    newfile="${newfile/_/-}"    # Change the underscore to a hyphen
    mv "$file" "$newfile"       # Make the change
done

以下のTonyのコメントに基づいて、より一般的なバージョンは次のようになります。

IFS="\n"                          # Handle files with spaces in the names
for file in ABS*; do
    newfile="${file/foo/bar}"     # Replace foo with bar
    newfile="${newfile/baz/quux}" # Replace baz with quux (repeat as needed)
    if [[ "$file" == "$newfile" ]]; then
        echo "Not renaming $file - no change decreed."
    elif [[ -f "$newfile" ]]; then
        echo "Not renaming $file - $newfile already exists."
    else
        mv -- "$file" "$newfile"       # Make the change
    fi
done

おすすめ記事