How to apply shell command to each line of a command output?
Suppose I have some output from a command (such as ls -1
):
a
b
c
d
e
...
I want to apply a command (say echo
) to each one, in turn. E.g.
echo a
echo b
echo c
echo d
echo e
...
What's the easiest way to do that in bash?
Solution 1:
It's probably easiest to use xargs
. In your case:
ls -1 | xargs -L1 echo
The -L
flag ensures the input is read properly. From the man page of xargs
:
-L number
Call utility for every number non-empty lines read.
A line ending with a space continues to the next non-empty line. [...]
Solution 2:
You can use a basic prepend operation on each line:
ls -1 | while read line ; do echo $line ; done
Or you can pipe the output to sed for more complex operations:
ls -1 | sed 's/^\(.*\)$/echo \1/'