acs005
acs005

Reputation: 192

AWK - OFS is not working with FS character set

Is there any spell that anyone who uses awk will fail with OFS at least once?

I have the following file:

someone.txt

LN_A,FN_A<[email protected]>;
LN_B,FN_B<[email protected]>;

And, I need:

FN_A,LN_A,aa
FN_B,LN_B,bb   

Initially, I tried the following with the below output:

awk -F'[,<@]' -v OFS=',' '{print $2 $1 $3}' someone.txt

FN_ALN_Aaa
FN_BLN_Bbb

After doing some research, I found that sometimes the record needs to be reconstructed. So, I tried the following, assuming changing NF will reconstruct the record.

awk -F'[,<@]' -v OFS=',' 'NF=3 {print $2 $1 $3}' someone.txt

FN_ALN_Aaa
FN_BLN_Bbb

Then, I tried this:

awk -F'[,<@]' -v OFS=',' 'NF=3; {print $2 $1 $3}' someone.txt
LN_A,FN_A,aa
FN_ALN_Aaa
LN_B,FN_B,bb
FN_BLN_Bbb

Then, this to reconstruct the record, still no luck:

awk -F'[,<@]' -v OFS=',' '{$1=$1} {print $2 $1 $3}' someone.txt

FN_ALN_Aaa
FN_BLN_Bbb

This one worked, but not as expected:

awk -F'[,<@]' -v OFS=',' '{$1=$1} {print $0}' someone.txt

LN_A,FN_A,aa,xyz.com>;
LN_B,FN_B,bb,xyz.com>;

Finally, I managed with the following:

awk -F'[,<@]' '{print $2 "," $1 "," $3}' someone.txt

FN_A,LN_A,aa
FN_B,LN_B,bb

PS:

  1. I know there are many questions on the same line, but I don't think this it as a duplicate as it is not working - at least for me. :-)
  2. I am using GNU Awk 3.1.7

Upvotes: 1

Views: 311

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133518

In case you are ok with sed could you please try following(written as per your shown samples). Using sed's ability to store matched regex in memory and using it while substituting section of sed, since sed is based on s/old/new pattern.

sed 's/\([^,]*\),\([^<]*\)<\([^@]*\)\(.*\)/\2,\1,\3/'  Input_file

Upvotes: 1

vintnes
vintnes

Reputation: 2030

OFS is generated when print eats a raw (unquoted) comma

I would do this:

$ awk -F'[,<@]' -v OFS=, '{print $2,$1,$3}' someone.txt

FN_A,LN_A,aa
FN_B,LN_B,bb

Upvotes: 1

Related Questions