且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 sed/awk 替换逗号分隔字符串中的第 n 列/字段?

更新时间:2023-09-03 19:22:10

在awk程序中让shell插入索引:

Have the shell interpolate the index in the awk program:

echo "1,2,3,4" | awk -F, -v OFS=, '{$'$index'="NEW"; print }'

注意最初的单引号 awk 程序是如何分成三个部分的,一个单引号开头的 '{$',插入的索引值,然后是程序的单引号剩余部分.

Note how the originally single quoted awk program is split in three parts, a single quoted beginning '{$', the interpolated index value, followed by the single quoted remainder of the program.