在正则表达式中使用诸如捕获组之类的东西进行大括号扩展的最佳方法是什么。例如:
touch {1,2,3,4,5}myfile{1,2,3,4,5}.txt
导致数字和 25 个不同文件的所有排列。但如果我只想让第一个和第二个数字相同的文件像1myfile1.txt
, 2myfile2.txt
,... 一样,这显然是行不通的。因此,我想知道最好的方法是什么?我正在考虑捕获第一个数字,然后再次使用它。理想情况下没有琐碎的循环。
谢谢!
在正则表达式中使用诸如捕获组之类的东西进行大括号扩展的最佳方法是什么。例如:
touch {1,2,3,4,5}myfile{1,2,3,4,5}.txt
导致数字和 25 个不同文件的所有排列。但如果我只想让第一个和第二个数字相同的文件像1myfile1.txt
, 2myfile2.txt
,... 一样,这显然是行不通的。因此,我想知道最好的方法是什么?我正在考虑捕获第一个数字,然后再次使用它。理想情况下没有琐碎的循环。
谢谢!
不使用正则表达式,而是使用for 循环和序列(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
MTwarog 的答案变体少了一个管道/子流程:
$ echo {1..5} | tr ' ' '\n' | xargs -I '{}' touch {}myfile{}.txt
$ ls -1 *myfile*
1myfile1.txt
2myfile2.txt
3myfile3.txt
4myfile4.txt
5myfile5.txt
您可以使用 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 - 通过触摸命令的文件名(创建文件)