I am wondering how to use Awk to process every 2 lines of data instead of every one. By default the record separator (RS) is set to every new line, how can I change this to every 2 lines.
4.1. 1 Record Splitting with Standard awk By default, the record separator is the newline character. This is why records are, by default, single lines. To use a different character for the record separator, simply assign that character to the predefined variable RS .
RT is set each time a record is read. It contains the input text that matched the text denoted by RS , the record separator. This variable is a gawk extension. In other awk implementations, or if gawk is in compatibility mode (see section Command Line Options), it is not special. A side note about NR and FNR .
Awk ORS is an Output equivalent of RS. Each record in the output will be printed with this delimiter. Following is an awk ORS example: $ awk 'BEGIN{ORS="=";} {print;}' student-marks Jones 2143 78 84 77=Gondrol 2321 56 58 45=RinRao 2122 38 37 65=Edwin 2537 78 67 45=Dayan 2415 30 47 20=
Record Separators (/V)Specify a comma-delimited string of separator bytes that can be expressed in hex format (for example: /VX5B,X6C,X7C) or character format (for example: /V$,%,@) . The default record separator if none is indicated on the /V command as a single byte, hex15.
It depends of what you want to achieve, but one way is to use the getline
instruction. For each line, read next one and save it in a variable. So you will have first line in $0
and second one in even_line
:
getline even_line
Divide&Conquer: do it in two steps:
NR%2==0 {print ""}
BEGIN {RS=""}
Advantage: In the second awk
process you have all fields of the two lines accessible as $1 to $NF
.
awk '{print}; NR%2==0 {print ""}' data | \
awk 'BEGIN {RS=""}; {$1=$1;print}'
Note:$1=$1
is used here to enforce an update on $0
(the whole record).
This guaranties that the output prints the two-line record on one line.
Once you modify a field in your program when you process the two-line records this is no longer required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With