tags:

views:

88

answers:

5

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?

+1  A: 

You can use a for loop:

for file in * ; do
   echo "$file"
done

Note that if the command in question accepts multiple arguments, then using xargs is almost always more efficient as it only has to spawn the utility in question once instead of multiple times.

Michael Aaron Safyan
+2  A: 

You can use a basic prepend operation on each line:

ls -1 | while read line ; do echo echo $line ; done

Or you can pipe the output to sed for more complex operations:

ls -1 | sed 's/^\(.*\)$/echo \1/'
Trey
The sed command doesn't seem to work: `sh: cho: not found a sh: cho: not found` Looks like it's taking the `e` in echo to be a sed command or something.
Alex
Dennis Williamson
@Alex: change the double quotes to single quotes.
Dennis Williamson
Ah, it wasn't the quotes -- I just missed the `s` for substitution. But this just prints out lines like `echo foo`, etc. Not executing the `echo`.
Alex
@Alex: That is correct the lines are not executed. The while example is much more flexible and will simply execute the commands (which is why I put "echo echo ..." so echo would actually be displayed)
Trey
+4  A: 

It's probably easiest to use xargs. In your case:

ls -1 | xargs -L1 echo
Michael Mrozek
`ls` automatically does `-1` in a pipe.
Dennis Williamson
@Dennis, doesn't look like it: `ls | xargs -L2 echo` and `ls -1 | xargs -L2 echo` give two different outputs. The former being all on one line.
Alex
@Alex: I get the same output.
Dennis Williamson
+1  A: 
for s in `cmd`; do echo $s; done

If cmd has a large output:

cmd | xargs -L1 echo
Marcelo Cantos
if `cmd` has spaces in its output, the first one will fail.
Dennis Williamson
+2  A: 

BASH FAQ entry #1

BASH Pitfalls entry #1

Ignacio Vazquez-Abrams
+1, +1, also: [Parsing ls](http://mywiki.wooledge.org/ParsingLs)
Dennis Williamson