Question

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!

Was it helpful?

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

OTHER TIPS

Using awk it is much simpler:

[[ $(wc -l < file) -eq 2 ]] && awk 'NR==2{$0=$0 RS "some chars"} 1' file
This is a
 new line Test
some chars

This will only produce (augmented) output in case the input line count is 2:

 echo "This is a
 new line Test" | 
  awk \
  'NR>2 {exit} {l=l $0 "\n"}  END {if (NR==2) printf "%s%s\n", l, "some chars"}'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top