重命名文件的 Shell 脚本
我根据在这里找到的示例编写了一个小型 shell 脚本:https://bbs。 archlinux.org/viewtopic.php?id=36305
它采用这个:
bash-3.2$ ls
test 001 test 002 test 003 test 004
并将其变成:
bash-3.2$ ls
001 002 003 004 rename.sh
但是它给了我这个错误(即使它有效):
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'
虽然它工作正常,但很高兴看到我在哪里搞砸了,我认为默认情况下它会将文件放在同一目录中(这是所需的输出)。
#!/bin/bash
ls | while read -r FILE
do
mv -v "$FILE" `echo $FILE | awk -F ' ' '{print $2}'`
done
预先感谢您帮助我纠正错误的代码。
I wrote a small shell script based on an example I found here: 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么要使用 ls 和 while 循环的额外过程?只需使用带有 shell 扩展的 for 循环即可。这是首选方式
why are you using
ls
with an extra process to while loop? Just use a for loop with shell expansion. This is preferred way邮递员几乎已经有了。对于 rename.sh,awk 命令不返回任何内容,因此实际上 shell 尝试执行以下命令:
因此出现错误消息“缺少目标文件”,
您可以通过测试脚本的文件名(硬编码或 $0)来修复此问题,并且仅当 $FILE 等于脚本名称时才执行 mv 命令。
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:
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.
我确实喜欢这个,它完美地改变了文件名。你可以像下面这样尝试。
I did like this and it is perfectly changing the filenames. You may try like below.