在unix单行代码中将*.foo更改为*.bar
我试图将给定目录中后缀为“.foo”的所有文件转换为包含相同基名但后缀修改为“.bar”的文件。我可以使用 shell 脚本和 for 循环来完成此操作,但我想编写一个单行代码来实现相同的目标。
目标:
输入:*.foo
输出:*.bar
这是我尝试过的:
find . -name "*.foo" | xargs -I {} mv {} `basename {} ".foo"`.bar
这很接近,但不正确。结果:
输入:*.foo
输出:*.foo.bar
关于为什么给定后缀未被基本名称识别的任何想法? “.foo”周围的引号是可有可无的,省略它们结果是一样的。
I am trying to convert all files in a given directory with suffix ".foo" to files containing the same basename but with suffix modified to ".bar". I am able to do this with a shell script and a for loop, but I want to write a one-liner that will achieve the same goal.
Objective:
Input: *.foo
Output: *.bar
This is what I have tried:
find . -name "*.foo" | xargs -I {} mv {} `basename {} ".foo"`.bar
This is close but incorrect. Results:
Input: *.foo
Output: *.foo.bar
Any ideas on why the given suffix is not being recognized by basename? The quotes around ".foo" are dispensable and the results are the same if they are omitted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
虽然
basename
可以处理文件扩展名,但使用 shell 参数扩展功能更容易:带有
basename
的代码不起作用,因为basename
是仅运行一次,然后 xargs 每次都会看到{}.bar
。Although
basename
can work on file extensions, using the shell parameter expansion features is easier:Your code with
basename
doesn't work because thebasename
is only run once, and then xargs just sees{}.bar
each time.示例:
Example:
for x in $(find .-name "*.foo");执行 mv $x ${x%%foo}bar;完毕
for x in $(find . -name "*.foo"); do mv $x ${x%%foo}bar; done
准备好后删除
echo
。Remove
echo
when ready.如果您已经安装了
mmv
,则可以执行.
If you have installed
mmv
, you can do.
为什么不使用“重命名”而不是脚本或循环。
RHEL:
重命名 foo bar .*foo
Debian:
重命名 's/foo/bar/' *.foo
Why don't you use "rename" instead of scripts or loops.
RHEL:
rename foo bar .*foo
Debian:
rename 's/foo/bar/' *.foo