Search code examples
stringbashsedpipechain

bash: append new line/string/text if input string has 2 lines


i got following output and want to test whether its line count (e.g. wc -l) is equal to 2. if so, i want to append something. It must use only chain pipes.

start input:

echo "This is a
new line Test"

goal output:

"This is a
 new line Test
 some chars"

But only if start input line count equals 2.

i tried already something like:

echo "This is a
new line Test" | while read line ; do lines=$(echo "$lines\n$line") ; echo $all ... ; done

But none of the ideas got to the solution. Using sed/awk, etc is ok, only it should be a chained pipe.

Thanks!


Solution

  • awk '1; END {if (NR <= 2) print "another line"}' file
    

    Here's another way just for fun: bash version 4

    mapfile lines <file; (IFS=; echo "${lines[*]}"); ((${#lines[@]} <= 2)) && echo another line
    

    better bash: tee into a process substitution

    $ seq 3 | tee >( (( $(wc -l) <= 2 )) && echo another line )
    1
    2
    3
    
    $ seq 2 | tee >( (( $(wc -l) <= 2 )) && echo another line )
    1
    2
    another line
    
    $ seq 1 | tee >( (( $(wc -l) <= 2 )) && echo another line )
    1
    another line