Truncate output after X lines and print message if and only if output was truncated
A note of warning:
When you do:
cmd | head
and if the output is truncated, that could cause cmd
to be killed by a SIGPIPE, if it writes more lines after head
has exited. If it's not what you want, if you want cmd
to keep running afterwards, even if its output is discarded, you'd need to read but discard the remaining lines instead of exiting after 10 lines have been output (for instance, with sed '1,10!d'
or awk 'NR<=10'
instead of head
).
So, for the two different approaches:
output truncated, cmd may be killed
cmd | awk 'NR>5 {print "TRUNCATED"; exit}; {print}'
cmd | sed '6{s/.*/TRUNCATED/;q;}'
Note that the mawk
implementation of awk
accumulates a buffer-full of input before starting processing it, so cmd
may not be killed until it has written a buffer-full (8KiB on my system AFAICT) of data. That can be worked-around by using the -Winteractive
option.
Some sed
implementations also read one line in advance (to be able to know which is the last line when using the $
address), so with those, cmd
may only be killed after it has output its 7th line.
output truncated, the rest discarded so cmd is not killed
cmd | awk 'NR<=5; NR==6{print "TRUNCATED"}'
cmd | sed '1,6!d;6s/.*/TRUNCATED/'
You can use AWK:
seq -f 'line %.0f' 20 | awk 'NR <= 5; NR > 5 { print "...Output truncated. Only showing first 5 lines..."; exit }'
This prints the first five lines (if any) as-is; if it sees a line beyond that, it outputs the truncation message and exits.
You can specify the exit code to use, if you want to implement conditional processing:
seq -f 'line %.0f' 20 | awk 'NR <= 5; NR > 5 { exit 1 }' || echo ...Output truncated. Only showing first 5 lines...