如何使用SED / AWK替换一个逗号分隔的字符串的第n列/字段? [英] How to replace the nth column/field in a comma-separated string using sed/awk?
问题描述
假设我有一个字符串
"1,2,3,4"
现在我要替换,如通过一些不同的值串的第3字段
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程序索引:
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屋!