如何在 bash 通配中重用匹配值?

如何在 bash 通配中重用匹配值?

我想知道是否可以重用通配符路径中匹配的任何内容? (就像通常可以通过正则表达式替换来完成一样?)

我知道以下示例还有其他解决方案,但我只是将其用作我所要求的示例:假设file_1.txt, file_2.txt, ..., file_100.txt当前文件夹中有文件,我想将它们重命名为asdf_1_qwer.txt, asdf_2_qwer.txt, ..., asdf_100_qwer.txt.当然,我可以将它们与 匹配file_*.txt,但是我可以以某种方式重用匹配的任何内容*来指定目标文件名吗?

答案1

虽然 shell 中没有与正则表达式捕获组直接等效的内容,但您所描述的内容通常是使用变量完成的。例如:

$ for f in file_*.txt; do
   number="${f/file_/}" 
   number="${number/.txt/}" 
   printf 'The number from file "%s" is "%d"\n' "$f" "$number"
done
The number from file "file_1.txt" is "1"
The number from file "file_2.txt" is "2"
The number from file "file_3.txt" is "3"

或者,使用sed而不是shell 字符串操作:

$ for f in file_*.txt; do    
    number=$(sed -E 's/^file_([0-9]+)\.txt/\1/' <<<"$f"); 
    printf 'The number from file "%s" is "%d"\n' "$f" "$number"; 
done
The number from file "file_1.txt" is "1"
The number from file "file_2.txt" is "2"
The number from file "file_3.txt" is "3"

相关内容