1

I want to perform below tasks,

1) print word if word count of line = 1

2) print 4th word if word count of line > 3

3) print blank line in all other cases

Input file is,

cat file.txt
Hi there I welcome you
Hi there You
Hi
Hi there
Hi there I welcome you all

Expected Output is,

welcome

Hi

welcome

When I am using below code, it is giving me output with additional blank line, which is not expected.

cat file.txt | awk '{ if (NF>3) {print $4} else if (NF==1) {print $1} else {print "\n"} }'
welcome


Hi


welcome

I have resolved this by using below code,

cat file.txt | awk '{ if (NF>3) {print $4} else if (NF==1) {print $1} else {print $10000} }'
welcome

Hi

welcome

However I want to understand what went wrong and why else statement is being executed twice and giving me unexpected output?

2

It is because print statement by default adds a newline at the end of the string it is printing. When used with \n it prints a double new-line as you see with the output. Use printf instead

awk '{ if (NF>3) {print $4} else if (NF==1) {print $1} else printf "\n" }' file

Without the explicit branch constructs, if..else if..else, you can just do

awk 'NF>3 { print $4; next } NF==1 { print $1; next } { printf "\n" }'
1

The print command always adds a newline. So print "\n" prints the newline you specified plus the one it added.

You can use print "" or printf "\n".

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.