Bash脚本正则表达式匹配1或2位数

时间:2015-01-16 21:57:49

标签: regex bash

我正在编写一个Bash脚本来从文件名中提取部件号。文件名命名为:part-number-N.jpg或part-number-NN.jpg,其中“N”是数字。

在此脚本中,“$ files”只是目录中文件的列表。

for f in $files; do 
  fileName=$(basename $f)
  tmp=${fileName%.jpg}
  partNo=${tmp%-[0-9]}
done

如何更新此脚本以删除字符串末尾最后两位数的连字符?

2 个答案:

答案 0 :(得分:2)

您可以使用extended globs

shopt -s extglob
partNo="${tmp%-[[:digit:]]?([[:digit:]])}"

此外,您可以更好地将文件存储在数组(files=(file1 file2 "file with embedded spaces in name"..))中并循环遍历数组 - for file in "${files[@]}"。同时双引号变量

答案 1 :(得分:0)

迟到的答案

您还可以在循环中使用sed来操作文件名:

for f in $files/*; do
    newFile=$(basename $f | sed 's/-[0-9][0-9]*//')
    echo $newFile
done

<强>输出

part-number-N.jpg  ->  part-number.jpg
part-number-NN.jpg ->  part-number.jpg