How to print 1st field and last 2 fields together and the rest of the fields after it using awk?

Hi experts,

I need to print the first field first then last two fields should come next and then i need to print rest of the fields.

Input :

a1,abc,jsd,fhf,fkk,b1,b2
a2,acb,dfg,ghj,b3,c4
a3,djf,wdjg,fkg,dff,ggk,d4,d5

Expected output:

a1,b1,b2,abc,jsd,fhf,fkk
a2,b3,c4,acb,dfg,ghj
a3,d4,d5,djf,wdjg,fkg,dff,ggk

I got how to print the first and last two fields together ,but not sure how to print the rest of the fields after this

 
awk -F ',' '{
print $1,$(NF-1),$NF}' infile
 
$ awk -F"," '{i=$(NF-1);j=$NF;for(k=NF;k>=4;k--){$k=$(k-2);};$2=i;$3=j} {print $0}' aak
a1 b1 b2 abc jsd fhf fkk
a2 b3 c4 acb dfg ghj
a3 d4 d5 djf wdjg fkg dff ggk
1 Like
awk -F, '{A=$1","$(NF-1)","$NF;sub($(NF-1)","$NF,"");$1=A}1' OFS="," file
1 Like
$ sed "s/\([^,]*\)\(.*\)\(,[^,]*,.*\)$/\1\3\2/" file
a1,b1,b2,abc,jsd,fhf,fkk
a2,b3,c4,acb,dfg,ghj
a3,d4,d5,djf,wdjg,fkg,dff,ggk
1 Like

Another approach:

awk -F, '{$1=$1 FS $(NF-1) FS $NF}NF=NF-2' OFS=, file
1 Like
with open("a.txt") as f:
 for line in f:
  line=line.replace("\n","")
  words=line.split(",")
  words=[words[0]]+words[len(words)-2:]+words[1:len(words)-2]
  print(",".join(words))
1 Like

Thank you all for your valuable inputs it helped me.