Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass command output as multiple arguments to another command

Tags:

linux

shell

unix

I want to pass each output from a command as multiple argument to a second command, e.g.:

grep "pattern" input

returns:

file1
file2
file3

and I want to copy these outputs, e.g:

cp file1  file1.bac
cp file2  file2.bac
cp file3  file3.bac

How can I do that in one go? Something like:

grep "pattern" input | cp $1  $1.bac
like image 542
yorgo Avatar asked Oct 30 '15 08:10

yorgo


People also ask

How do you use the output of one command in another command?

You can make it do so by using the pipe character '|'. Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on.

How do you pass the output of a program to another in Linux?

In Linux, for redirecting output to a file, utilize the ”>” and ”>>” redirection operators or the top command. Redirection allows you to save or redirect the output of a command in another file on your system. You can use it to save the outputs and use them later for different purposes.

How do you echo output of command?

The echo command writes text to standard output (stdout). The syntax of using the echo command is pretty straightforward: echo [OPTIONS] STRING... Some common usages of the echo command are piping shell variable to other commands, writing text to stdout in a shell script, and redirecting text to a file.

How pass awk output to another command?

You just need to use command substitution: date ... $(last $USER | ... | awk '...') ...


2 Answers

You can use xargs:

grep 'pattern' input | xargs -I% cp "%" "%.bac"
like image 64
choroba Avatar answered Sep 21 '22 19:09

choroba


You can use $() to interpolate the output of a command. So, you could use kill -9 $(grep -hP '^\d+$' $(ls -lad /dir/*/pid | grep -P '/dir/\d+/pid' | awk '{ print $9 }')) if you wanted to.

like image 24
Chris Jester-Young Avatar answered Sep 19 '22 19:09

Chris Jester-Young