Monday, June 13, 2016

Substituting part of the field with awk using values from other fields - example with special characters

If you have a file and need to substitute part of the field 2: [b37]$1,$2 with combined fields 3 and 4, for example _$3_$4:

1 text[b37]$1,$2 3 4
2 text[b37]$1,$2 5 6

Use awk with sub commands, making sure you escape characters [ and $.

awk '{ sub(/\[b37\]\$1,\$2$/,"_"$3"_"$4, $2) }1' file.txt

Output file:
1 text_3_4 3 4
2 text_5_6 5 6