在目录中有以下格式的文件:*-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
Run Code Online (Sandbox Code Playgroud)
所需目录:
$ ls *.txt
asdf.txt bnm.txt ghjk.txt iop.txt l.txt qwer.txt tyui.txt zxcv.txt
Run Code Online (Sandbox Code Playgroud)
我想到的第一个解决方案看起来有点像这个丑陋的黑客:
ls *-* | cut -d- -f1 | sed 's/.*/mv "\0-foo-bar.txt" "\0.txt"/' > rename.sh && sh rename.sh
Run Code Online (Sandbox Code Playgroud)
上面的解决方案动态创建一个脚本来重命名文件.ls根据http://mywiki.wooledge.org/ParsingLs,该解决方案还尝试解析其输出不是一件好事.
使用像这样的shell脚本可以更优雅地解决这个问题:
for i in *-*
do
mv "$i" "`echo $i | cut -f1 -d-`.txt"
done
Run Code Online (Sandbox Code Playgroud)
上述解决方案使用循环重命名文件.
有没有办法在一行中解决这个问题,这样我们就不必显式编写循环脚本,或生成脚本,或调用新的或当前的shell(即避免使用sh,bash ,.等命令) ?
你试过重命名命令吗?
例如:
rename 's/-foo-bar//' *-foo-bar.txt
Run Code Online (Sandbox Code Playgroud)
如果你没有这种信息也是,我会用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
Run Code Online (Sandbox Code Playgroud)