Search code examples
bashxargs

Get the sequence number of xargs command


echo a b c | xargs -n 1 will output:

a
b
c

Is there any way to get the output with sequence number as below:

a1
b2
c3

Thank you!

Hatjhie


Solution

  • Use awk and its special NR placeholder:

    echo a b c | xargs -n 1 | awk '{print $1NR}'
    

    Result:

    a1
    b2
    c3
    

    You can pipe those results again. Notice we set a placeholder called % (using -I %) which we can reuse. For instance:

    echo a b c | xargs -n 1 | awk '{print $1NR".zip"}' | xargs -I % git archive -o % HEAD