Insert strings/values between text

Hello Guru,
I'm trying to insert a value between 2 fields (between last and second last field) But end up the script actually replacing the value in the second last field. What should i put to fix the problem?

Input File:

apple,mango,grape,lemon

Expected output:

apple,mango,grape,0,lemon
awk -F, 'BEGIN{OFS=","}{$(NF-1)="0";print}' input

my output (grape is missing)

apple,mango,0,lemon

Thanks

Try changing your code to:

awk -F, 'BEGIN{OFS=","}{$(NF-1)=$(NF-1) OFS "0";print}'

or

awk -F, 'BEGIN{OFS=","}{$NF="0" OFS $NF;print}'
1 Like

Hai Don,
Thanks it works perfectly:b:. But can you explain a bit your second method. I just don't get how the code insert the value 0 in the middle.

Thanks again. :slight_smile:

Please try the below.

 awk -F, '{$4="1,"$4}1' OFS=,  test.txt 
1 Like

Both methods are the same; the 1st one adds ,0 to the end of the next to the last field; the 2nd one adds 0, to the start of the last field. Putting two strings next to each other when assigning a string value to a variable concatenates those strings. Both use OFS (the awk output field separator) instead of a literal comma in case you change from a comma separated value file format to use some other field separator at some point in the future.

1 Like

Understood. Thank you guys for your helped. :b: