开发者

Extract Lines when Column K is empty with AWK/Perl

I have data that looks like this:

foo 78 xxx
bar    yyy
qux 99 zzz
xuq    xyz

They are tab delimited. How can I extract lines where column 2 is empty, yielding

bar    yyy
xuq    xyz

I tried this but d开发者_如何学Pythonoesn't seem to work:

awk '$2==""' myfile.txt 


You need to specifically set the field separator to a TAB character:

> cat qq.in
  foo     78      xxx
  bar             yyy
  qux     99      zzz
  xuq             xyz
> cat qq.in | awk 'BEGIN {FS="\t"} $2=="" {print}'
  bar             yyy
  xuq             xyz

The default behaviour for awk is to treat an FS of SPACE (the default) as a special case. From the man page:

In the special case that FS is a single space, fields are separated by runs of spaces and/or tabs and/or newlines. (my italics)


perl -F/\t/ -lane 'print unless $F[1] eq q//' myfile.txt

Command Switches

  • -F tells Perl what delimiter to autosplit on (tabs in this case)
  • -a enables autosplit mode, splitting each line on the specified delimiter to populate an array @F
  • -l automatically appends a newline "\n" at the end of each printed line
  • -n processes the file line-by-line
  • -e treats the first quoted argument as code and not a filename


grep -e '^.*\t\t.*$' myfile.txt

Will grep each line consisting of characters-tab-tab-characters (nothing between tabs).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜