我有名爲「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