Bash脚本循环遍历文件名以在特定索引处删除

时间:2012-01-01 15:21:23

标签: file bash rename

我有大量的文件名如下:

nn - xxxxxxxxxxxxxx-OOO.ext

nn始终为两位数,xxxxx为文本的可变长度。 (-OOO的后缀在所有文件中都是静态的)。循环中应该将文件重命名为:

xxxxxxxxxxxxxx.ext

因此删除了nn -(总是前5个字符)和-OOO

2 个答案:

答案 0 :(得分:1)

您可以使用两个子字符串操作来执行此操作:

$ name="nn - xxxx x xx xx xxxxx-OOO.ext"
$ part1=${name:5}                   # substring starting at position 5
$ part2=${part1%-OOO.ext}           # remove `-OOO.ext` at the end of $part1
$ final="$part2".ext
$ echo $final
xxxx x xx xx xxxxx.ext
$ mv "$name" "$final"

答案 1 :(得分:0)

echo $file_name | sed "s/.*-\s*\(.*\)-.*/\1.ext/"将按照您在OP中的要求为您提供“xxxxxxx.ext”。