Consume stdin several times in a bash script

My script takes a stream to stdin. I want to pass the first line to stdout regardless of whether and grep the remaining lines with -v, and also pass them to standard output.

I developed a solution using tee, but I wonder if this will always output output headbefore exiting grep? What if headit was replaced with something that was blocked 20 minutes before printing something, will this output appear at the end of stdout after exiting grep?

tee >(head -n 1) >(tail -n +2 | grep -v -E "$PATTERN")

If the order is not guaranteed, what is the right way to do this?

+4
source share
3 answers

, tee, head tail.

read , grep :

$ printf "foo\nbar\nquux\n" | { read v; echo "$v"; grep -v bar; }
foo
quux

, awk :

$ printf "foo\nbar\nquux\n" | awk 'NR==1{print;next} !/bar/'
foo
quux
+4

, . - , , . , , .

read line && printf '%s\n' "$line"
tee >(grep -v -E "$PATTERN")
+1

, sed:

printf "Line1\nfoo\nbar\n" | sed '1n;/bar/d'

:

Line1
foo

... 1 , , bar, .

+1

Source: https://habr.com/ru/post/1533420/


All Articles