21

I have lines of data that contain single column and two columns. What I want to do is to extract lines that contain only 2 columns.

0333 foo
 bar
23243 qux

yielding only:

0333 foo
23243 qux

Note that they are tab separated, even for lines with only one column you have tab at the beginning.

What's the way to do it?

I tried this but fail:

awk '$1!="";{print $1 "\t" $2}' myfile.txt

enter code here
neversaint
  • 60,904
  • 137
  • 310
  • 477

3 Answers3

35

You need to use the NF (number of fields) variable to control the actions, such as in the following transcript:

$ echo '0333 foo
>  bar
> 23243 qux' | awk 'NF==2{print}{}'
0333 foo
23243 qux

This will print the line if the number of fields is two, otherwise it will do nothing. The reason I have the (seemingly) strange construct NF==2{print}{} is because some implementations of awk will print by default if no rules are matched for a line. The empty command {} guarantees that this will not happen.

If you're lucky enough to have one of those that doesn't do this, you can get away with:

awk 'NF==2'

but the first solution above will work in both cases.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    Why not `awk 'NF==2{print}{}{}{}{}{}{}'` ?? NF==2 suffices. – Mark Edgar Aug 03 '10 at 08:54
  • 2
    @Mark, some implementations of `awk` will print by default if you don't specify a default action. My code works on those ones as well. You bods are spoilt with your GNU awk, some of us have to write portable code :-) I'll clarify. – paxdiablo Aug 03 '10 at 09:13
  • @ pax, An awk implementation which behaves the way you describe would be pretty broken. As far as I know, awk dates to v7, and the manual there pretty clearly describes its behavior: "for example, the program length > 72 prints all input lines whose length exceeds 72 characters." – Mark Edgar Apr 26 '12 at 16:24
9
awk 'NF==2' file
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
6
awk '(NF==2){print}' test.txt
Vijay
  • 65,327
  • 90
  • 227
  • 319