There is a not well known feature of GNU sed. You can add the e
flag to the s
command and then sed executes whatever is in the pattern space and replaces the pattern space with the output if that command.
If you are really only interested in the output of the echo commands, you might try this GNU sed example, which eliminates the temporary variable, the loop (and the xargs as well):
echo {1..3} | sed -r 's/([^ ])+/echo "line \1 here"\n/ge
- it fetches one token (i.e. whatever is separated by the spaces)
- replaces it with
echo "line \1 here"\n
command, with \1
replaced by the token
- then executes echo
- puts the output of the echo command back into pattern space
- that means it outputs the result of the three echos
But an even better way to get the desired output is to skip the execution and do the transformation directly in sed, like this:
echo {1..3} | sed -r 's/([^ ])+ ?/line \1 here\n/g'