Nan Xiao
Nan Xiao

Reputation: 17467

Why does the output contain a blank line at the end?

My file is just one line:

$ cat employee-one-line.txt
101,John Doe:102,Jason Smith:103,Raj Reddy:104,Anand Ram:105,Jane Miller
$

But executing the following awk script, it prints a redundant empty line at end:

$ awk -F, 'BEGIN{ RS=":" } {print $2}' employee-one-line.txt
John Doe
Jason Smith
Raj Reddy
Anand Ram
Jane Miller

$

Why is there a blank line at end?

Upvotes: 0

Views: 67

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74596

Since you have set the record separator to a colon, the last record is 105,Jane Miller, followed by a newline character. print adds an ORS (output record separator) to the end of things that it prints, so you end up with two.

The default behaviour would be that awk consumes the newline as the record separator, then adds it back in whenever you print.

In order to make awk swallow the newline in this case, one option would be to add it to your field separator:

awk -F'[,\n]' 'BEGIN{ RS=":" } {print $2}' file

Upvotes: 3

CiaPan
CiaPan

Reputation: 9571

Once you defined RS=':', a newline is no longer a record separator, so the newline terminating your file got appended to "Jane Miller".

Upvotes: 0

Related Questions