user2854333
user2854333

Reputation: 640

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".

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

Upvotes: 2

Views: 55

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133428

You need not to save output into a variable and then print it(its not required in here), we can simply use ternary operators in print function of awk itself, like as follows:

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

Explanation: Simple explanation would be, setting field separator as , and using print statement of awk here, where checking condition if NF(number of fields in current line) is 6 then print 3rd and 4th fields separated with , else print only 3rd field.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

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

Upvotes: 1

Related Questions