使用shell脚本批量重命名

问题描述:

我有一个文件夹,其中的文件名为

I have a folder with files named as

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
...

我哪里做错了?

我现在已经加引号了,但我现在明白了

I have put in the quotes now, but I get this now

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

它以某种方式试图将文件重命名为相同的名称.这是怎么回事?

It is somehow trying to rename the file to the same name. How is that happening?

那是因为 bash for 用空格 ' ' 分割元素,所以你命令它移动 'input代码>'到'(1)'.

That is because bash for split the element with space ' ' so you are commanding it to move 'input' to '(1)'.

解决这个问题的方法是使用 IFS 变量告诉 bash 按新行拆分.

The way to solve this is to tell bash to split by new line using IFS variable.

像这样:

IFS=$'\n'

然后执行您的命令.

但是,我建议您使用 find 来代替使用 -exec 命令来执行此操作.

However, I suggest you to use find to do this instead using -exec command.

例如:

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

注意:我是凭记忆写的,我确实测试过,所以让我们试着调整一下.

NOTE: I write this from memory and I did test this so let try and adjust it.

希望这会有所帮助.