开发者

Easy shell solution to execute a command for each line of stdout [duplicate]

开发者 https://www.devze.com 2022-12-22 01:03 出处:网络
This question already has answers here: How to apply shell command to each line of a command output? (9 answers)
This question already has answers here: How to apply shell command to each line of a command output? (9 answers) Closed 6 years ago.

This should be an absurdly easy task: I want to take each line of the stdout of any old command, a开发者_StackOverflow中文版nd 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.)


That program is called xargs.

ls | grep foo | xargs -I %s mv %s bar/


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消