Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

bash - How can I send the out of the last pipe to two different commands?

So, I have text file with a a bunch of numbers, one number per line to be specific, so I do:- cat filename.txt|sort -n|head -1 to get the top number and I can do cat filename.txt|sort -n|tail -1 to get the bottom number. Just to be sure is there a way to send cat filename.txt|sort -n| and its output to two different commands in one line and have the out put (the highest number and the lowest number next to each other)

question from:https://stackoverflow.com/questions/65927990/how-can-i-send-the-out-of-the-last-pipe-to-two-different-commands

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do interesting things with tee and process substitutions, but the order of the output may not be stable (due to timing of processes)

sort -n filename.txt | tee >(tail -1 >/dev/tty) | head -1

In this case, I'd use sed to print the first and last line:

sort -n filename.txt | sed -n '1p; $p'

As @chepner suggests

... | sed -n '1p; $p' | paste - -     # tab separated

or

... | awk 'NR == 1 {first = $0} END {print first, $0}'   # space separated

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...