Thursday, February 22, 2024
76
rated 0 times [  76] [ 0]  / answers: 1 / hits: 54998  / 3 Years ago, sun, july 25, 2021, 7:03:48

I want merge (union) output from two different commands, and pipe them to a single command.



A silly example:



Commands I want to merge the output:



cat wordlist.txt
ls ~/folder/*


into:



wc -l


In this example, if wordlist.txt contains 5 lines and 3 files, I want wc -l to return 8.



$cat wordlist.txt *[magical union thing]* ls ~/folder/* | wc -l
8


How do I do that?


More From » command-line

 Answers
0

Your magical union thing is a semicolon... and curly braces:



    { cat wordlist.txt ; ls ~/folder/* ; } | wc -l


The curly braces are only grouping the commands together, so that the pipe sign | affects the combined output.



You can also use parentheses () around a command group, which would execute the commands in a subshell. This has a subtle set of differences with curly braces, e.g. try the following out:



    cd $HOME/Desktop ; (cd $HOME ; pwd) ; pwd
cd $HOME/Desktop ; { cd $HOME ; pwd ; } ; pwd


You'll see that all environment variables, including the current working directory, are reset after exiting the parenthesis group, but not after exiting the curly-brace group.



As for the semicolon, alternatives include the && and || signs, which will conditionally execute the second command only if the first is successful or if not, respectively, e.g.



    cd $HOME/project && make
ls $HOME/project || echo "Directory not found."

[#38650] Monday, July 26, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mance

Total Points: 198
Total Questions: 105
Total Answers: 128

Location: South Georgia
Member since Mon, Aug 16, 2021
3 Years ago
;