avermaet
avermaet

Reputation: 1593

Bash capturing in brace expansion

What would be the best way to use something like a capturing group in regex for brace expansion. For example:

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

results in all permutations of the numbers and 25 different files. But in case I just want to have files like 1myfile1.txt, 2myfile2.txt,... with the first and second number the same, this obviously doesn't work. Therefore I'm wondering what would be the best way to do this? I'm thinking about something like capturing the first number, and using it a second time. Ideally without a trivial loop.

Thanks!

Upvotes: 2

Views: 201

Answers (3)

markp-fuso
markp-fuso

Reputation: 34409

Variation on MTwarog's answer with one less 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

Upvotes: 3

M. Twarog
M. Twarog

Reputation: 2623

You can use AWK to do that:

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

Explanation:

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

Upvotes: 1

Gonzalo Matheu
Gonzalo Matheu

Reputation: 10064

Not using a regex but a for loop and sequence (seq) you get the same result:

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

Or tidier:

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

As an example, using echo instead of touch:

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

Upvotes: 4

Related Questions