Home > Blockchain >  How can I pipe lines of a given file into a shell command?
How can I pipe lines of a given file into a shell command?

Time:09-21

Let's say I have a req.txt containing some package's name.

~ » cat req.txt                                      
code
heroku
postman

What I want to achieve is a one-line command like:

~ » cat req.txt | snap install "$1" --classic 

CodePudding user response:

Use xargs like so:

cat req.txt | xargs -I{} snap install --name={}

Here:
-I{} : Replace occurrences of string {} with the names read from STDIN.

Alternatively, use this Perl one-liner:

cat req.txt | perl -lne 'system "snap install --name=$_"; '

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.

system : Executes a system command.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches

  • Related