[英]Shell script to rename files
I wrote a small shell script based on an example I found here: https://bbs.archlinux.org/viewtopic.php?id=36305 我根据在此找到的示例编写了一个小的Shell脚本: https : //bbs.archlinux.org/viewtopic.php?id=36305
it takes this: 它需要这个:
bash-3.2$ ls
test 001 test 002 test 003 test 004
and turns it into: 并将其转换为:
bash-3.2$ ls
001 002 003 004 rename.sh
However it gives me this error (even though it works): 但是它给了我这个错误(即使它可以工作):
bash-3.2$ ./rename.sh
mv: missing destination file operand after `rename.sh'
Try `mv --help' for more information.
`test 001' -> `001'
`test 002' -> `002'
`test 003' -> `003'
`test 004' -> `004'
Though it works correctly, it would be nice to see where I messed up, I assumed by default it would put the files in the same directory (this is the desired output). 尽管它可以正常工作,但是很高兴看到我在哪里搞砸了,我默认情况下会把文件放在同一目录中(这是所需的输出)。
#!/bin/bash
ls | while read -r FILE
do
mv -v "$FILE" `echo $FILE | awk -F ' ' '{print $2}'`
done
Thanks in advance for helping me correct my incorrect code. 在此先感谢您帮助我纠正错误的代码。
why are you using ls
with an extra process to while loop? 为什么要使用带有额外过程的
ls
进行while循环? Just use a for loop with shell expansion. 只需在外壳扩展中使用for循环即可。 This is preferred way
这是首选方式
#!/bin/bash
shopt -s nullglob
for file in *
do
if [ -f "$file" ];then
newfile="${file##* }"
mv "$file" $newfile"
fi
done
Postman almost has it. 邮差几乎拥有它。 For rename.sh, the awk command returns nothing so in effect you have the following command the shell attempts to execute:
对于rename.sh,awk命令不返回任何内容,因此实际上您具有以下shell尝试执行的命令:
mv rename.sh
hence the error message "missing destination file" 因此,错误消息“缺少目标文件”
you can fix this by testing for the filename of the script, either hardcoded or $0, and executing the mv command only if $FILE does equal the script name. 您可以通过测试脚本的文件名(硬编码或$ 0)并仅在$ FILE与脚本名相同时执行mv命令来解决此问题。
I did like this and it is perfectly changing the filenames. 我确实喜欢这样,并且它完美地更改了文件名。 You may try like below.
您可以尝试如下操作。
mkdir /root/test; touch my\ file{1..10}
vim rename.sh
#!/bin/bash
ls /root/test| while read -r FILE
do
mv -v /root/test/"$FILE" /root/test/`echo $FILE | awk -F" " '{print $2}'`
done
chmod +x rename.sh
./rename.sh
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.