matuslittva
matuslittva

Reputation: 163

Why is awk removing empty lines

I want to merge changes from two strings files into one with awk but it is deleting empty lines which are used in my files for better readability.

awk -F= '!a[$1]++' 1.strings 2.strings > results.strings

My files looks like:

"cart.title" = "Cart";
"cart.subtitle" = "Price";

"checkout.title" = "Checkout";

But my output is:

"cart.title" = "Cart";
"cart.subtitle" = "Price";
"checkout.title" = "Checkout";

But I want to keep that newline before checkout.

Upvotes: 2

Views: 79

Answers (1)

Ed Morton
Ed Morton

Reputation: 203324

Your script isn't removing newlines, it's removing some empty (possibly including lines of all spaces) lines. Given input like this:

$ printf 'foo\n\nbar\n'
foo

bar

this script will remove newlines (not your case):

$ printf 'foo\n\nbar\n' | awk -v ORS= '1'
foobar$

while this script will remove empty lines (your case):

$ printf 'foo\n\nbar\n' | awk 'NF'
foo
bar

Your script will only remove an empty line if there was another empty line before it, e.g. if the first input line was empty, as it only prints lines with unique $1 values across ALL lines, empty or not. To keep all empty lines use:

$ awk -F= '!NF || !a[$1]++' file

"cart.title" = "Cart";
"cart.subtitle" = "Price";

"checkout.title" = "Checkout";

Upvotes: 3

Related Questions