ディレクトリ内の複数のファイル名で、記号で区切られた 2 つの文字列を入れ替える

ディレクトリ内の複数のファイル名で、記号で区切られた 2 つの文字列を入れ替える

author - nameいくつかの本のファイル名のような文字列を に変更したいのですがname - author

ls * | sed -r 's/(.+) - (.+).pdf/mv \2 - \1.pdf/' | sh

多分それは シンボルで区切られた任意の長さの文字列を切り替える そしてsed で複数のファイルの名前を変更する

これは機能しません

for file in *; do mv "$file" "$(echo "$file" | sed -r 's/(.+) - (.+).pdf/\2 - \1.pdf/')"

どちらも

rename 's/\([.]+\) - \([.]+\)\.pdf/\2 - \1\.pdf/' *

これはうまくいく

rename 's/(.+) - (.+).pdf/\2 - \1.pdf/' *

答え1

これを試して

% ls -1                                                                                                       
001-foobar.pdf
002-foobar.pdf
003-foobar.pdf

コード

% rename -n 's/([^-]+)-([^\.]+)\.pdf/$2-$1.pdf/' *.pdf                                                          
001-foobar.pdf -> foobar-001.pdf
002-foobar.pdf -> foobar-002.pdf
003-foobar.pdf -> foobar-003.pdf

注記

(テストがOKなら -n スイッチを削除してください)

警告 同じ名前の他のツールも存在しますが、これが実行できる場合とできない場合がありますので注意してください。

次のコマンド(GNU)を実行すると

$ file "$(readlink -f "$(type -p rename)")"

そして結果は次のようになります

.../rename: Perl script, ASCII text executable

以下を含まない:

ELF

これは適切なツールのようです =)

Debianそうでない場合は、次のようにして派生をデフォルト (通常は既にデフォルトになっています) にしますUbuntu

$ sudo update-alternatives --set rename /path/to/rename

(コマンド/path/to/renameのパスに置き換えてくださいperl's rename


このコマンドがない場合は、パッケージマネージャーを検索してインストールするか、手動で行う


最後になりましたが、このツールは元々、Perl の父である Larry Wall によって作成されました。

答え2

ファイル名はパターンに従っておりauthor - name.pdf、 と の両方にauthor、スペースで囲まれた文字nameを除く任意の有効な文字を含めることができると想定しています-

find . -type f -name '* - *.pdf' \
    -execdir sh -c 'b=${1% - *}; e=${1#* - }; mv "$1" "${e%.pdf} - $b.pdf"' sh {} \;

これは、パターンに一致する名前を持つ現在のディレクトリ内のすべての通常ファイルを検索します* - *.pdf

このようなファイルごとに、サブシェルが実行されます。サブシェルは次のことを行います。

b=${1% - *}  # pick out the start of the filename
e=${1#* - }  # pick out the end of the filename

# Combine $b and $e into a new filename while removing ".pdf" from
# the end of the original filename and adding it to the end of
# the new filename instead.
mv "$1" "${e%.pdf} - $b.pdf"

テスト中:

$ ls -l
total 0
-rw-r--r--  1 kk  wheel  0 Aug 30 11:31 arr! - Boaty McBoatface.pdf
-rw-r--r--  1 kk  wheel  0 Aug 30 11:30 hello world - bingo-night!.pdf

$ find . -type f -name '* - *.pdf' -execdir sh -c 'b=${1% - *}; e=${1#* - }; mv "$1" "${e%.pdf} - $b.pdf"' sh {} \;

$ ls -l
total 0
-rw-r--r--  1 kk  wheel  0 Aug 30 11:31 Boaty McBoatface - arr!.pdf
-rw-r--r--  1 kk  wheel  0 Aug 30 11:30 bingo-night! - hello world.pdf

もう一度実行すると、名前が元に戻ります。

関連情報