大括号捕获中的重击捕获

时间:2019-10-03 13:04:02

标签: bash brace-expansion

在正则表达式中使用捕获组之类的大括号扩展的最佳方法是什么。例如:

touch {1,2,3,4,5}myfile{1,2,3,4,5}.txt

产生数字和25个不同文件的所有排列。但是,如果我只想拥有1myfile1.txt2myfile2.txt等文件,并且第一个和第二个数字相同,则显然不起作用。因此,我想知道什么是最好的方法? 我正在考虑获取第一个数字,然后第二次使用它。理想情况下,没有微不足道的循环。

谢谢!

3 个答案:

答案 0 :(得分:4)

不使用正则表达式而是使用for loop和序列(seq),您将得到相同的结果:

for i in $(seq 1 5); do touch ${i}myfile${i}.txt; done

或更整齐的

 for i in $(seq 1 5); 
 do 
   touch ${i}myfile${i}.txt; 
 done

例如,使用echo代替touch

➜ for i in $(seq 1 5); do echo ${i}myfile${i}.txt; done
1myfile1.txt
2myfile2.txt
3myfile3.txt
4myfile4.txt
5myfile5.txt

答案 1 :(得分:2)

您可以使用AWK来做到这一点:

echo {1..5} | tr ' ' '\n' | awk '{print $1"filename"$1".txt"}' | xargs touch

说明:

  

echo {1..5}-打印数字范围
  tr'''\ n'-将数字拆分为单独的行
  awk'{print $ 1“ filename” $ 1}'-使您可以使用以前打印的数字格式化输出
  xargs touch-将文件名传递给touch命令(创建文件)

答案 2 :(得分:2)

使用更少的管道/子流程来改变MTwarog的答案:

$ echo {1..5} | tr ' ' '\n' | xargs -I '{}' touch {}myfile{}.txt
$ ls -1 *myfile*
1myfile1.txt
2myfile2.txt
3myfile3.txt
4myfile4.txt
5myfile5.txt