使用 Bash 重命名文件,删除前缀和后缀
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12031081/
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
Renaming files with Bash, removing prefix and suffix
提问by óscar López
I want to rename a bunch of files using bash, transforming this file pattern:
我想使用 bash 重命名一堆文件,转换此文件模式:
prefix - name - suffix.txt
Into this one:
进入这个:
name.txt
For that I wrote the following script:
为此,我编写了以下脚本:
find . -name "*.txt" | while read f
do
mv "${f}" "${f/prefix - /}"
done
find . -name "*.txt" | while read f
do
mv "${f}" "${f/ - suffix/}"
done
It works, but I'd like to perform the renaming using a single loop. Is it possible?
它有效,但我想使用单个循环执行重命名。是否可以?
回答by chepner
Another approach, for fun, using regular expressions:
另一种方法,为了好玩,使用正则表达式:
regex='prefix - (.*) - suffix.txt'
for f in *.txt; do
[[ $f =~ $regex ]] && mv "$f" "${BASH_REMATCH[1]}.txt"
done
Actually, using the simple pattern '*.txt' here has two problems:
实际上,这里使用简单的模式 '*.txt' 有两个问题:
- It's too broad; you may need to apply the regex to a lot of non-matching files.
- If there are a lotof files in the current directory, the command line could overflow.
- 它太宽泛了;您可能需要将正则表达式应用于许多不匹配的文件。
- 如果当前目录中有很多文件,命令行可能会溢出。
Using findcomplicates the procedure, but is more correct:
使用find使过程复杂化,但更正确:
find . -maxdepth 1 -regex 'prefix - .* - suffix.txt' -print0 | \
while read -d '' -r; do
[[ $REPLY =~ $regex ]] && mv "$REPLY" "${BASH_REMATCH[1]}.txt"
done
回答by Steve
If you have access to GNU sed, you could use some regex to perform something like:
如果您有权访问GNU sed,则可以使用一些正则表达式来执行以下操作:
for i in *.txt; do mv "$i" "$(echo $i | sed -r 's/([^-]*)\s-\s(.*)\s-\s([^-]*)\.txt/.txt/')"; done
回答by mpapis
you could use this:
你可以用这个:
find . -name "*.txt" -print0 | awk -v RS="find . -name "*.txt" -print0 |
awk -v RS="# open your dir with emacs
emacs /path/to/your/dir
" -v ORS="##代码##" '{
print ##代码##;
sub(/^prefix - /,"");
sub(/ - suffix.txt$/,".txt");
print ##代码##;
}' |
xargs -0 -n 2 mv
" -v ORS="##代码##" '{print ##代码##;sub(/^prefix - /,""); sub(/ - suffix.txt$/,".txt"); print ##代码##; }' | xargs -0 -n 2 mv
which could be written more clearly as:
可以更清楚地写成:
##代码##回答by kev
If you have emacsinstalled. You can use the diredfeature.
如果你已经emacs安装了。您可以使用该dired功能。
In bash:
在bash:
##代码##
In emacs:
在emacs:
- Press *%Enter
\.txt$Enterto mark alltxtfiles. - Press %rEnter
.*- \(.*\) -.*Enter\1.txtEnterto rename.
- 按标记所有文件。*%Enter
\.txt$Entertxt - 按重命名。%rEnter
.*- \(.*\) -.*Enter\1.txtEnter

