Insert field values in a record using awk command

Hi Friends,

Below is my input file with "|" (pipe) as filed delimiter:
My Input File:

HDR|F1|F2||||F6|F7

I want to inser values in the record for field 4 and field 5.
Expected output

HDR|F1|F2||F4|F5|F6|F7

I am able to append the string to the end of the record, but not in between the fileds. Below is my awk command:

awk '    
     BEGIN{FS = "|";RS = "\r\n"};
     FNR=NR{x = "F4";y="F5";z="|"
                     print $0 z x z y;
            } 
                    
             }' $Iputfile > $OutputFile

My Output:

HDR|F1|F2||||F6|F7|F4|F5

Please suggest me on how to insert the values in-between the fields.

Thanks in advance

akshay@nio:/tmp$ cat file
HDR|F1|F2||||F6|F7
akshay@nio:/tmp$ awk '{ for(i=1;i<=NF;i++){ if(!length($i)){ $i="F"last+1} last=$i; gsub(/[^0-9]*/,"",last)  }}1' FS=\| OFS=\| file
HDR|F1|F2|F3|F4|F5|F6|F7

---------- Post updated at 01:33 PM ---------- Previous update was at 01:28 PM ----------

---

I see you edited expected output

add like this

awk '{$5 = "F4"; $6 = "F5"}1' FS=\| OFS=\| file
HDR|F1|F2||F4|F5|F6|F7

---------- Post updated at 01:54 PM ---------- Previous update was at 01:33 PM ----------

OR try something like this

awk -vfield='4=F4,5=F5'  'BEGIN{split(field,S,/,/); for(i in S){ split(S,D,/=/);F[D[1]+1]=D[2] }}{for(i in F)$i=F}1' FS=\| OFS=\|  file

Or much more simply:

awk -F'|' '{$4 = "F4"; $5 = "F5"}1' OFS='|' "$Iputfile" > "$OutputFile"

but you should verify that $Iputfile is correct. From your output file variable name I would have expected $Inputfile or $InputFile .

1 Like

Thanks Don, it worked fine... :slight_smile: