[英]Renaming multiple files in one line of shell
在目录中有以下格式的文件:* -foo-bar.txt。
示例目录:
$ ls *-*
asdf-foo-bar.txt ghjk-foo-bar.txt l-foo-bar.txt tyui-foo-bar.txt
bnm-foo-bar.txt iop-foo-bar.txt qwer-foo-bar.txt zxcv-foo-bar.txt
所需目录:
$ ls *.txt
asdf.txt bnm.txt ghjk.txt iop.txt l.txt qwer.txt tyui.txt zxcv.txt
我想到的第一个解决方案看起来有点像这个丑陋的黑客:
ls *-* | cut -d- -f1 | sed 's/.*/mv "\0-foo-bar.txt" "\0.txt"/' > rename.sh && sh rename.sh
上面的解决方案动态创建一个脚本来重命名文件。 此解决方案还尝试解析ls
的输出,根据http://mywiki.wooledge.org/ParsingLs ,这不是一件好事。
使用像这样的shell脚本可以更优雅地解决这个问题:
for i in *-*
do
mv "$i" "`echo $i | cut -f1 -d-`.txt"
done
上述解决方案使用循环重命名文件。
有没有办法在一行中解决这个问题,这样我们就不必显式编写循环脚本,或生成脚本,或调用新的或当前的shell(即避免使用sh,bash ,.等命令) ?
你试过重命名命令吗?
例如:
rename 's/-foo-bar//' *-foo-bar.txt
如果你没有那个,我会使用find
, sed
和xargs
:
find . -maxdepth 1 -mindepth 1 -type f -name '*-foo-bar.txt' | sed 's/-foo-bar.txt//' | xargs -I{} mv {}-foo-bar.txt {}.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.