简体   繁体   English

在一行shell中重命名多个文件

[英]Renaming multiple files in one line of shell

Problem 问题

In a directory there are files of the format: *-foo-bar.txt. 在目录中有以下格式的文件:* -foo-bar.txt。

Example directory: 示例目录:

$ 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

Desired directory: 所需目录:

$ ls *.txt
asdf.txt  bnm.txt  ghjk.txt  iop.txt  l.txt  qwer.txt  tyui.txt  zxcv.txt

Solution 1 解决方案1

The first solution that came to my mind looks somewhat like this ugly hack: 我想到的第一个解决方案看起来有点像这个丑陋的黑客:

ls *-* | cut -d- -f1 | sed 's/.*/mv "\0-foo-bar.txt" "\0.txt"/' > rename.sh && sh rename.sh

The above solution creates a script, on the fly, to rename the files. 上面的解决方案动态创建一个脚本来重命名文件。 This solution also tries to parse the output of ls which is not a good thing to do as per http://mywiki.wooledge.org/ParsingLs . 此解决方案还尝试解析ls的输出,根据http://mywiki.wooledge.org/ParsingLs ,这不是一件好事。

Solution 2 解决方案2

This problem can be solved more elegantly with a shell script like this: 使用像这样的shell脚本可以更优雅地解决这个问题:

for i in *-*
do
    mv "$i" "`echo $i | cut -f1 -d-`.txt"
done

The above solution uses a loop to rename the files. 上述解决方案使用循环重命名文件。

Question

Is there a way to solve this problem in a single line such that we do not have to explicitly script a loop, or generate a script, or invoke a new or the current shell (ie avoid sh, bash, ., etc. commands)? 有没有办法在一行中解决这个问题,这样我们就不必显式编写循环脚本,或生成脚本,或调用新的或当前的shell(即避免使用sh,bash ,.等命令) ?

Have you tried the rename command? 你试过重命名命令吗?

For example: 例如:

rename 's/-foo-bar//' *-foo-bar.txt

If you don't have that available, I would use find , sed , and xargs : 如果你没有那个,我会使用findsedxargs

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM