In awk, how to ignore error line when printing $2, but $2 does not exist in error line

Viewed 101

I have a text file (xxx.txt) with this format:

kw1 kw2 kw3 kw4
kw1 kw2 kw3 kw4
...

but sometimes, the line is abnormal, like this:

kw1 

My shell command is

cat xxx.txt|awk '{ print $2;print $3}'

How to ignore the abnormal line, and continue printing?

3 Answers

Based on your shown samples try following once. We could use only single print to print the two fields with a new line here

awk 'NF>=3{print $2 ORS $3}' Input_file

Answering your title question how to ignore error line when print $2 but $2 it not exist in error line let file.txt content be

kw1 kw2 kw3 kw4
kw1 kw2 kw3 kw4
kw1
kw1 kw2 kw3 kw4

then

awk '($2!=""){print $2;print $3}' file.txt

output

kw2
kw3
kw2
kw3
kw2
kw3

Explanation: if you try to access field which is not present in given line you get empty string. I process lines only where given field is not empty.

Related