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".
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
CodePudding user response:
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