I need to pipe the last record verbatim to an external command. I found the following snippet here, but it unconditionally removes ORS from last record. I want to remove it only if RS was not present in the input file.

awk 'NR > 1 { print h } { h = $0 } END { ORS = ""; print h }' inputfile

pii_ke

Ответов: 2

Ответы (2)

Your logic is backwards and double-negative making it hard to understand. If I understand you correctly it's not that you want to remove ORS if RS was not present, it's that you only want to add ORS if RS was present.

The simplest way is to use gawk for RT so each output record is terminated by the same string that terminated the input record.

awk 'NR > 1 { printf "%s%s", $0, RT }' inputfile

A portable approach, not relying on the GNU Awk RT variable, is to add a dummy record to your input: a dummy record which is not followed by the separator.

Then the input is strictly separated and you just have two cases to handle: you either have a blank second-to-last record, in which case the true last record is third-to-last. Or else, the second-to-last record is the true last one.

If you keep track of the most recently seen nonblank record in a variable, you can print that record at the end of processing.

There are various ways to add material to the end of input. For instance, some useful uses of cat:

 (cat real_input; printf "dummy_rec" ) | awk '...'

or

 cat real_input dummy_suffix | awk '...'

2022 WebDevInsider