6

I have a CSV file like

CK,ck
XYZ,xyz,xyzs
ABC,abc,abcs
PQR,pqr,pqrs
LMN,lmn,
IJK,ijk,

I have to check if something is written in column 3 except whitespace, then display the whole line.the output will be:

XYZ,xyz,xyzs
ABC,abc,abcs
PQR,pqr,pqrs

4 Answers 4

7

A sed approach:

sed -n '/[^,]*,[^,]*,[^, ]\+/p' file

Or a grep solution:

grep -oE '^[^,]*,[^,]*,[^, ]+' file

And awk:

awk -F, '$3 ~ /[^, ]+/' file
6
  • Good one chaos, nice and clean.
    – Relic
    Commented Sep 4, 2014 at 16:54
  • you need to add a start of line anchor to your grep regex. Also, -E should suffice, no need for -P
    – iruvar
    Commented Sep 4, 2014 at 17:19
  • @1_CR edited the answer
    – chaos
    Commented Sep 4, 2014 at 17:31
  • Love the awk example, had to lookup how it was evaluated and learned something today, thanks!
    – jidar
    Commented Sep 4, 2014 at 17:43
  • 1
    $3 ~ /[^[:blank:]]/ might be even better
    – iruvar
    Commented Sep 4, 2014 at 18:15
4

Try:

$ awk -F, '$3 && $3 != " "' file
XYZ,xyz,xyzs
ABC,abc,abcs
PQR,pqr,pqrs

or:

$ awk -F, '$3 ~ /[^[:blank:]]/' file
0
3

You could do something like this in awk :

awk -F',' '{gsub(/[ \t]+$/,"",$3)}$3' foo.csv

This will remove trailing whitespaces and only print if there's something left in the third field.

1

Using GNU awk:

awk -F, '$3' input_file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .