tags:

views:

40

answers:

3

Hi,

This should be an absurdly easy task: I want to take each line of the stdout of any old command, and use each to execute another command with it as an argument.

For example:

ls | grep foo | applycommand 'mv %s bar/'

Where this would take everything matching "foo" and move it to the bar/ directory.

(I feel a bit embarrassed asking for what is probably a ridiculously obvious solution.)

+4  A: 

That program is called xargs.

ls | grep foo | xargs -I %s mv %s bar/
Chris Jester-Young
xargs also lets you insert arguments in the middle of the command by specifying a substitution string. i.e. `xargs -I FILE mv FILE bar/`
Martin
@Martin: Thanks, I learnt something new! Will update my answer accordingly.
Chris Jester-Young
also mv has a --target option. so just: | xargs mv --target=bar/
pixelbeat
@pixelbeat: Thanks! I was trying to model my answer after what the OP wanted (with `%s` and all), but obviously in this case, your solution is even better.
Chris Jester-Young
+3  A: 
ls | grep foo | while read FILE; do mv "$FILE" bar/; done

This particular operation could be done more simply, though:

mv *foo* bar/

Or for a recursive solution:

find -name '*foo*' -exec mv {} bar/ \;

In the find command {} will be replaced by the list of files that match.

John Kugelman
Almost right: when doing `-exec ... +`, the `{}` must immediately precede the `+`. You can use the `;` form though: `-exec mv {} bar/ ';'`.
Chris Jester-Young
A: 

for your case, do it simply like this.

for file in *foo*
do
   if [ -f "$file" ];then
      mv "$file" /destination
   fi
done

OR just mv it if you don't care about directories or files

mv *foo* /destination
ghostdog74