bashbrace-expansion

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!


Solution

  • 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)