[英]Renaming multiple files in one line of shell
在目錄中有以下格式的文件:* -foo-bar.txt。
示例目錄:
$ ls *-*
asdf-foo-bar.txt ghjk-foo-bar.txt l-foo-bar.txt tyui-foo-bar.txt
bnm-foo-bar.txt iop-foo-bar.txt qwer-foo-bar.txt zxcv-foo-bar.txt
所需目錄:
$ ls *.txt
asdf.txt bnm.txt ghjk.txt iop.txt l.txt qwer.txt tyui.txt zxcv.txt
我想到的第一個解決方案看起來有點像這個丑陋的黑客:
ls *-* | cut -d- -f1 | sed 's/.*/mv "\0-foo-bar.txt" "\0.txt"/' > rename.sh && sh rename.sh
上面的解決方案動態創建一個腳本來重命名文件。 此解決方案還嘗試解析ls
的輸出,根據http://mywiki.wooledge.org/ParsingLs ,這不是一件好事。
使用像這樣的shell腳本可以更優雅地解決這個問題:
for i in *-*
do
mv "$i" "`echo $i | cut -f1 -d-`.txt"
done
上述解決方案使用循環重命名文件。
有沒有辦法在一行中解決這個問題,這樣我們就不必顯式編寫循環腳本,或生成腳本,或調用新的或當前的shell(即避免使用sh,bash ,.等命令) ?
你試過重命名命令嗎?
例如:
rename 's/-foo-bar//' *-foo-bar.txt
如果你沒有那個,我會使用find
, sed
和xargs
:
find . -maxdepth 1 -mindepth 1 -type f -name '*-foo-bar.txt' | sed 's/-foo-bar.txt//' | xargs -I{} mv {}-foo-bar.txt {}.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.