使用Bash重命名文件,删除前缀和后缀 [英] Renaming files with Bash, removing prefix and suffix
本文介绍了使用Bash重命名文件,删除前缀和后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用bash重命名一堆文件,以转换此文件模式:
I want to rename a bunch of files using bash, transforming this file pattern:
prefix - name - suffix.txt
进入这一个:
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?
推荐答案
另一种使用正则表达式的方法很有趣:
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
实际上,在这里使用简单模式'* .txt'存在两个问题:
Actually, using the simple pattern '*.txt' here has two problems:
- 范围太广;您可能需要将正则表达式应用于许多不匹配的文件.
- 如果当前目录中有很多个文件,则命令行可能会溢出.
- It's too broad; you may need to apply the regex to a lot of non-matching files.
- If there are a lot of files in the current directory, the command line could overflow.
使用find
使过程复杂,但更正确:
Using find
complicates the procedure, but is more correct:
find . -maxdepth 1 -regex 'prefix - .* - suffix.txt' -print0 | \
while read -d '' -r; do
[[ $REPLY =~ $regex ]] && mv "$REPLY" "${BASH_REMATCH[1]}.txt"
done
这篇关于使用Bash重命名文件,删除前缀和后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文