Bash 在大括号扩展中捕获

Bash capturing in brace expansion

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

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

产生数字的所有排列和 25 个不同的文件。但是如果我只想拥有 1myfile1.txt2myfile2.txt、...这样的文件,并且第一个和第二个数字相同,这显然是行不通的。因此,我想知道最好的方法是什么? 我正在考虑诸如捕获第一个数字并再次使用它之类的事情。理想情况下没有简单的循环。

谢谢!

不使用正则表达式而是 for loop and sequence (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

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

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

解释:

echo {1..5} - prints range of numbers
tr ' ' '\n' - splits numbers to separate lines
awk '{print "filename"}' - enables you to format output using previously printed numbers
xargs touch - passes filenames to touch command (creates files)

MTwarog 答案的变体少了一个pipe/subprocess:

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