从文件名中删除子字符串

wis*_*eri 2 shell ubuntu

我有名称格式为“NAME-xxxxxx.tedx”的文件,我想删除“-xxxxxx”部分。x 都是数字。正则表达式"\-[0-9]{1,6}"匹配子字符串,但我不知道如何从文件名中删除它。

知道如何在 shell 中做到这一点吗?

Sha*_*hin 5

如果您安装了rename命令perl 版本,您可以尝试:

rename 's/-[0-9]+//' *.tedx
Run Code Online (Sandbox Code Playgroud)

演示:

[me@home]$ ls
hello-123.tedx  world-23456.tedx
[me@home]$ rename 's/-[0-9]+//' *.tedx
[me@home]$ ls
hello.tedx  world.tedx
Run Code Online (Sandbox Code Playgroud)

如果这意味着覆盖现有文件,则此命令足够智能,不会重命名文件:

[me@home]$ ls
hello-123.tedx  world-123.tedx  world-23456.tedx
[me@home]$ rename 's/-[0-9]+//' *.tedx
world-23456.tedx not renamed: world.tedx already exists
[me@home]$ ls
hello.tedx  world-23456.tedx  world.tedx
Run Code Online (Sandbox Code Playgroud)