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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12674823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:25:23  来源:igfitidea点击:

Renaming multiple files in one line of shell

bashshell

提问by Susam Pal

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

方案一

The first solution that came to my mind looks somewhat like this ugly hack:

我想到的第一个解决方案看起来有点像这个丑陋的黑客:

ls *-* | cut -d- -f1 | sed 's/.*/mv "
for i in *-*
do
    mv "$i" "`echo $i | cut -f1 -d-`.txt"
done
-foo-bar.txt" "
rename 's/-foo-bar//' *-foo-bar.txt
.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 lswhich 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 脚本更优雅地解决:

find . -maxdepth 1 -mindepth 1 -type f -name '*-foo-bar.txt' | sed 's/-foo-bar.txt//' | xargs -I{} mv {}-foo-bar.txt {}.txt

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 (i.e. avoid sh, bash, ., etc. commands)?

有没有办法在一行中解决这个问题,这样我们就不必显式编写循环脚本,或生成脚本,或调用新的或当前的 shell(即避免使用 sh、bash、. 等命令) ?

回答by Tim Pote

Have you tried the renamecommand?

您是否尝试过重命名命令?

For example:

例如:

##代码##

If you don't have that available, I would use find, sed, and xargs:

如果您没有可用的,我会使用find, sed, 和xargs

##代码##