LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   awk command for different delimiters (http://www.linuxquestions.org/questions/programming-9/awk-command-for-different-delimiters-4175426443/)

ip_address 09-09-2012 11:41 PM

awk command for different delimiters
 
Hello everyone,

I am trying to write a command to print the third field of each line in the text file "mixed_format.txt" where some lines are delimited by colon and some are delimited by space.

Code:

$ cat mixed_format.txt
1:2:3:4:5
1 2 3 4 5
abc:cvb:mkl:45:45
23 45 68 45 55

I used this command

Code:

awk '{ if( $0 ~ /:/ ) { FS=":"; } else { FS =" "; } print $3 }' mixed_format.txt
but it is not giving me any output. Could you guys please give me some pointers how to solve it.

PS: If I issue awk command with a delimiter specified using -F switch, I get correct output

Code:

$ awk -F: '{print $3}' mixed_format.txt
Output

Code:

3

mkl

Code:

$ awk -F" " '{print $3}' mixed_format.txt
Output

Code:



3

68


Thanks!!!

firstfire 09-10-2012 12:19 AM

Hi.

Code:

$ awk -F '[: ]' '{print $3}' in
3
3
mkl
68

[..] is a character list. Thir regular expression matches either : or single space. Note that it treats single space as a delimiter. If your delimiters may consist of multiple spaces, then try
Code:

$ awk -F ':| +' '{print $3}' in
3
3
mkl
68


David the H. 09-10-2012 01:34 AM

Here are a few useful awk references:
http://www.grymoire.com/Unix/Awk.html
http://www.gnu.org/software/gawk/man...ode/index.html
http://www.pement.org/awk/awk1line.txt
http://www.catonmat.net/blog/awk-one...ined-part-one/

The first link is a very useful tutorial. Look particularly at the sections on the field and record separator settings.

ip_address 09-10-2012 03:48 AM

Thank you!!!


All times are GMT -5. The time now is 09:53 PM.