Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have a text file delimited by | (multiple records).

field1|field2|field3|field4|field5

i wanted to check if field3 is blank or contains "space" characters only, if it is blank or space, i wanted the whole line to show up.

what unix command can i use to do this ?

Michael

share|improve this question
add comment

4 Answers

up vote 11 down vote accepted

$ 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}'

share|improve this answer
2  
+1, awk is the tool of choice for all (non-hyper-complex) field-based manipulation. Some prefer Perl but that's using a hammer to kill a fly in my opinion. –  paxdiablo Jul 9 '09 at 0:27
add comment

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
share|improve this answer
    
More readable than awk for this trivial situation if y' ask me (which nobody did ;)) –  Tom Newton Jul 9 '09 at 7:08
add comment

My random attempt using grep would be:

grep -E '^[^|]*\|[^|]*\| *[^| ]+ *\|' file
share|improve this answer
    
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 8 '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
add comment

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.

share|improve this answer
    
linux is a form of unix. Most things that are in linux are in other unixes. –  Rory Jul 16 '09 at 12:40
    
was this comment necessary? Sed, Awk, Grep and the like are SIMILAR across *NIX and BSD systems, but not always the same. –  Tedd Johnson Jul 23 '09 at 19:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.