
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
筆記
(測試正常時刪除 -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
。
對於每個這樣的文件,都會執行一個子 shell。子 shell 執行以下操作:
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
再次運行它會將名稱交換回原來的名稱。