3

A csv file with multiple records is delimited by |.

field1|field2|field3|field4|field5

I want to check if field3 is blank or contains "space" characters only. If it is blank or space, the whole line should show up.

Jonas Stein
  • 406
  • 5
  • 14
Michael Ellick Ang
  • 2,039
  • 3
  • 14
  • 15

5 Answers5

10
$ echo "1|2||4" | awk  -F'|' '$3 ~ /^[ \t]*$/   {print $0}'

1|2||4

$ echo "1|2|  |4" | awk  -F'|' '$3 ~ /^[ \t]*$/   {print $0}'

1|2|  |4

$ echo "1|2|  3|4" | awk  -F'|' '$3 ~ /^[ \t]*$/   {print $0}'
Jonas Stein
  • 406
  • 5
  • 14
James
  • 2,232
  • 1
  • 13
  • 19
3

You can also use the cut command to pull out the third field and then test the value:

$ echo "field1|field2|field3|field4|field5" | cut -d '|' -f 3
field3
Chad Huneycutt
  • 2,116
  • 1
  • 16
  • 14
1

My random attempt using grep would be:

grep -E '^[^|]*\|[^|]*\| *[^| ]+ *\|' file
JMusgrove
  • 1,223
  • 1
  • 8
  • 8
  • The trouble with this approach is that it isn't general, so if you want to select on the 14th field it would become hateful. – James Jul 08 '09 at 23:27
  • 1
    @James: Then try something like: "grep -E '^([^|]*\|){13} *[^| ]+ *\|' file" adjusting the value "13" appropriately – JMusgrove Jul 13 '09 at 22:38
0

I'm not certain about unix, but in linux you would want to use the sed command.

sed 's/||/\n/g' will make it so that if there are any blank fields it will add a new line. not certain how to get it to only check the 3rd field. sed 's/| |/\n/g' should work for only spaces.

Tedd Johnson
  • 71
  • 2
  • 10
0

Using Perl:

perl -F'\|' -lane 'print if $F[2] !~ /\S/' file

-a turns on autosplit mode, which splits the fields into array @F
-F'\|' sets the field delimiter to |
$F[2] is the 3rd field
!~ /\S/ tests for non-space characters (or empty)

Chris Koknat
  • 111
  • 3