如何使用 sed/awk 替换逗号分隔字符串中的第 n 列/字段? [英] How to replace the nth column/field in a comma-separated string using sed/awk?
问题描述
假设我有一个字符串
"1,2,3,4"
现在我想替换,例如字符串的第三个字段由一些不同的值.
Now I want to replace, e.g. the 3rd field of the string by some different value.
"1,2,NEW,4"
我使用以下命令设法做到了这一点:
I managed to do this with the following command:
echo "1,2,3,4" | awk -F, -v OFS=, '{$3="NEW"; print }'
现在要替换的列的索引应该作为变量传递.所以在这种情况下
Now the index for the column to be replaced should be passed as a variable. So in this case
index=3
如何将其传递给 awk?因为这行不通:
How can I pass this to awk? Because this won't work:
echo "1,2,3,4" | awk -F, -v OFS=, '{$index="NEW"; print }'
echo "1,2,3,4" | awk -F, -v OFS=, '{$($index)="NEW"; print }'
echo "1,2,3,4" | awk -F, -v OFS=, '{$$index="NEW"; print }'
感谢您的帮助!
推荐答案
在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.
这篇关于如何使用 sed/awk 替换逗号分隔字符串中的第 n 列/字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!