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
7

A sed approach:

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

Or a grep solution:

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

And awk:

awk -F, '$3 ~ /[^, ]+/' file
  • Good one chaos, nice and clean. – Relic Sep 4 '14 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 Sep 4 '14 at 17:19
  • @1_CR edited the answer – chaos Sep 4 '14 at 17:31
  • Love the awk example, had to lookup how it was evaluated and learned something today, thanks! – jidar Sep 4 '14 at 17:43
  • 1
    $3 ~ /[^[:blank:]]/ might be even better – iruvar Sep 4 '14 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
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

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.