Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Capture nth field bash

I have data in a file test.txt in below format.

abc,123,mno,xyz,1234
mno,123,abc,rpt,pqr,2345
xyz,456,uyt,rtp,rto,

I want to capture the 3rd field which I am able to achieve using

var=`awk  -F, '{print $3}' test.txt | sed "s/^[ \t]*//"`

I have run into a issue where 3rd field can be either "mno" or "abc,rpt".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I use the above logic I get output as

mno
abc
uyt

But I want output as

 mno
 abc,rpt    
 uyt,rtp

Any suggestions.

Regards

>Solution :

You can use

awk  -F, '{s=(NF==6?$3","$4:$3); print s}'

That is, if there are 6 fields, concatenate the third and fourth, else get the third field value only.

See the online demo:

#!/bin/bash
s='abc,123,mno,xyz,1234
mno,123,abc,rpt,pqr,2345
xyz,456,uyt,rtp,rto,'
awk  -F, '{s=(NF==6?$3","$4:$3); print s}'  <<< "$s"

Output:

mno
abc,rpt
uyt,rtp
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading