我有名为“NAME-xxxxxx.tedx”的文件,我想删除“-xxxxxx”部分。 x都是数字。 正则表达式"\-[0-9]{1,6}"
匹配子字符串,但我不知道如何从文件名中删除它。从文件名中删除子串
任何想法如何我可以在shell中做到这一点?
我有名为“NAME-xxxxxx.tedx”的文件,我想删除“-xxxxxx”部分。 x都是数字。 正则表达式"\-[0-9]{1,6}"
匹配子字符串,但我不知道如何从文件名中删除它。从文件名中删除子串
任何想法如何我可以在shell中做到这一点?
如果您已经安装了perl version of the rename
command,你可以尝试:
rename 's/-[0-9]+//' *.tedx
演示:
[[email protected]]$ ls
hello-123.tedx world-23456.tedx
[[email protected]]$ rename 's/-[0-9]+//' *.tedx
[[email protected]]$ ls
hello.tedx world.tedx
此命令如果覆盖现有文件,则足够智能以不重命名文件:
[[email protected]]$ ls
hello-123.tedx world-123.tedx world-23456.tedx
[[email protected]]$ rename 's/-[0-9]+//' *.tedx
world-23456.tedx not renamed: world.tedx already exists
[[email protected]]$ ls
hello.tedx world-23456.tedx world.tedx
echo NAME-12345.tedx | sed "s/-[0-9]*//g"
将给NAME.tedx
。所以,你可以使用一个循环和移动使用mv
命令文件:
for file in *.tedx; do
newfile=$(echo "$file" | sed "s/-[0-9]*//g")
mv "$file" $newfile
done
如果你想使用只是外壳
shopt -s extglob
for f in *-+([0-9]]).tedx; do
newname=${f%-*}.tedx # strip off the dash and all following chars
[[ -f $newname ]] || mv "$f" "$newname"
done