我有一个单行(g)awk脚本,它可以按预期工作:
'/pattern/ {$n="new string"}1'
现在,我想将上述内容与独立的(g)awk脚本以及其他命令一起使用,到目前为止,我仍无法理解如何使其工作。
我的文件开始于:
BEGIN {
FS = ","
OFS = FS
}
{
here goes my code
}
尤其是在代码语法稍有不同的情况下,我不确定在/ pattern /(放在方括号内还是在外面)的位置-但也许这是我弄错了的地方。
我对“ 1”的位置也有同样的疑问。
因此,我正在对此进行更新,因为我不确定以上内容是否足够清楚-我的错。
我有一个带有4个字段(1-4)的CSV文件,我想匹配字段#3中的特定模式,并在匹配该模式后,用新字符串替换所有该字段内容。
我可以用一个(g)awk衬垫执行以下操作:
awk -F, -v OFS="," '/pattern/ {$3="new string"}1
我想将上面的代码移动到awk脚本中,其中将存在其他命令,以实现相同的结果-即:
输入文件:
yellow, yellow and blue, yellow and red, blue
blue, yellow and blue, yellow and red, red
red, yellow and red, blue and red, blue
red, yellow and blue, yellow and blue, red
图案:红色 感兴趣的领域:#3 新字符串:tree
所需的输出:
yellow, yellow and blue, tree, blue
blue, yellow and blue, tree, red
red, yellow and red, tree, blue
red, yellow and blue, yellow and blue, red
AWK脚本包含三个部分-BEGIN,BODY和END。您的oneliner仅使用身体部位。等效脚本如下所示:
主体语法本身可以重复:
您打算做的可能是这样的:
If the pattern can match several fields on each line, you will use
gsub()
instead ofsub()
.Since the substitution is not limited to a specific field, it doesn't seem relevant to me to specify the field separator. In that case,
awk
doesn't provide an added value for this kind of substitution. Probably, as far as I can see,sed
will be faster thanawk
in this environment.