2010-08-22 146 views
3

重命名我有一個命名爲批量使用shell腳本

input (1).txt 
input (2).txt 
input (3).txt 
... 
input (207).txt 

如何重新命名這些文件

input_1.in 
input_2.in 
input_3.in 
... 
input_207.in 

我想這

for f in *.txt ; do mv $f `echo $f | sed -e 's/input\ (\(\d*\))\.txt/input_\1.in/'` ; done 

但是它給出了一個文件夾我

mv: target `(100).txt' is not a directory 
mv: target `(101).txt' is not a directory 
mv: target `(102).txt' is not a directory 
... 

我哪裏出錯了?


我已經把報價了,但我得到這個現在

mv: `input (90).txt' and `input (90).txt' are the same file 

它是某種試圖文件重命名爲相同的名稱。這是怎麼發生的?

回答

3

這是因爲bash的for與空間「」所以你是指揮它移動「input」到「(1)」分裂的元素。

解決此問題的方法是使用IFS變量告訴bash按新行拆分。

像這樣:

IFS=$'\n'

然後做你的命令。

但是,我建議您使用find來做這個,而不是使用-exec命令。

例如:

find *.txt -exec mv "{}" `echo "{}" | sed -e 's/input\ (\([0-9]*\))\.txt/input_\1.in/'` \;

注:我寫這從內存和我做了測試這個所以讓我們嘗試並進行調整。

希望這會有所幫助。

+0

這個'mv:'input(90).txt'和'input(90).txt'是同一個文件' – Lazer 2010-08-22 07:07:08

+0

我不認爲你可以使用'\ d'(從我記得的),嘗試使用'[0-9]'。 – NawaMan 2010-08-22 07:21:00

+0

謝謝! '[0-9]'工作。爲什麼'\ d'不工作? – Lazer 2010-08-22 07:36:16

3

你忘了引用你的論點。

... mv "$f" "$(echo "$f" | ...)" ; done 
3

不需要調用外部命令

#!/bin/bash 
shopt -s nullglob 
shopt -s extglob 
for file in *.txt 
do 
    newfile="${file//[)]/}" 
    newfile="${file// [(]/_}" 
    mv "$file" "${newfile%.txt}.in" 
done 
0
for f in *.txt ; do mv "$f" `echo $f | sed -e 's/input\ (\(\d*\))\.txt/input_\1.in/'` ; done 
1

正如you'v e已經修復,你需要引用$f的參數mv

至於你的第二個問題,sed不支持\d。您可以改用[0-9]