How to replace second column of csv file with a specific value “XYX”

awksed

To replace last field of csv file with xyz I use following command:

awk -F, '{$NF="xyz";}1' OFS=, file

How can I overwrite the second column of file with value xyz?

Best Answer

In awk the variable NF is the number of fields on the current line. You can refer to each field like $1,$2...$NF where $1 is the first field and $2 is the second field, upto $NF which is the last field on the current line (i.e. if NF is 5 then $NF is $5).

$ cat file
1,2,3,4,5

$ awk '$2="XYX"' FS=, OFS=, file
1,XYX,3,4,5