在bash shell中重命名一堆文件最簡單的方法是什麼?要將當前目錄中的每個*.ext
文件重命名爲*.otherext
?我接受使用perl或awk的解決方案,並不一定是純粹的bash。有任何想法嗎?在bash中使用perl或awk來改變多個文件的擴展名?
要清楚這將意味着:
mv a.ext a.otherext
mv b.ext b.otherext
...
etc. for all *.ext
在bash shell中重命名一堆文件最簡單的方法是什麼?要將當前目錄中的每個*.ext
文件重命名爲*.otherext
?我接受使用perl或awk的解決方案,並不一定是純粹的bash。有任何想法嗎?在bash中使用perl或awk來改變多個文件的擴展名?
要清楚這將意味着:
mv a.ext a.otherext
mv b.ext b.otherext
...
etc. for all *.ext
有幾個方法可以做到這一點。有一個rename
程序用Perl寫的:
rename 's/\.ext\z/.otherext/' *.ext
但也有另一種(不兼容)rename
各地的方案,爲此,你不得不這樣做:
rename .ext .otherext *.ext
還有一個叫mmv
程序:
mmv '*.ext' '#1.otherext'
使用普通的bash:
for i in *.ext; do mv -- "$i" "${i%.ext}.otherext"; done
使用普通的Perl:
perl -we 'for my $old (glob "*.ext") { (my $new = $old) =~ s/\.ext\z/.otherext/; rename $old, $new or warn "$old -> $new: $!\n"; }'
完美,謝謝!出於好奇,是否有相當於Python的一個班輪到你的Perl或是不可能的? – user248237dfsf 2013-02-25 05:07:59
對不起,我不知道python。 – melpomene 2013-02-25 05:08:19
簡單Bash版本的+1。順便說一句,不使用'--',另一種選擇是使用'./*。ext'而不是'* .ext'來選擇要迭代的文件。 – ruakh 2013-02-25 05:13:08
既然你問什麼是Python版本可能的樣子,我想我會添加它爲後人。
#!/usr/bin/python
from glob import glob
from os import rename
for f in glob("*.ext"):
rename(f, f[:-3] + "otherext")
的一個行版本(而不是好看):
python -c "import glob,os;[os.rename(f, f[:-3] + \"otherext\") for f in glob.glob(\"*.ext\")]"
謝謝,但我的意思是它作爲一個從shell的單線...我知道如何寫它作爲一個完整的腳本,但希望做一個快速的班輪。也許Python不適合這個? – user248237dfsf 2013-02-25 05:45:44
@ user248237添加了單行版本。 – squiguy 2013-02-25 06:01:44
一個Python的一行:
python -c "import shutil, glob; [shutil.move(i,i.replace('.txt','.ext')) for i in glob.glob('*.txt')]"
充分利用「和」,而不是轉義字符及替換功能
檢查此:http://theunixshell.blogspot.com/2012/12/changing-extension-of-large-number-of.html – Vijay 2013-02-25 06:37:10