如何使用 awk 打印变量而不是完整的匹配行?

How to have awk print variable instead of the full matched line?

下面的 awk 脚本打印出与预期不同的结果,我想知道为什么。我怎样才能让它按照我想要的方式运行?

Awk 脚本

$ cat script.awk 
/^This is/ {
    print "Block entered";

    my_var="value";
    print $my_var;
};

输入数据

$ cat input-data 
This is the text to match

预期产出

Block entered
value

实际产量

$ awk -f script.awk -- input-data 
Block entered
This is the text to match

anubhava 已经建议修复 OP 的代码;以下是对 OP 代码正在做什么的解释...

$ 用于引用当前行中的一个字段(例如,</code> == 第一个字段)所以 ...</p> <p><code>$myvar 变为 $value,但由于这是一个无效的字段引用 awk 默默地忽略它所以 ...

print $myvar 变为 print 但 ...

print(没有参数)表示打印当前(输入)行 ...

因此 This is the text to match

的输出

注意: 在 OP 提供的 link 之后(见上面的评论),看来 $value 实际上可能被视为 [=22 =] 给我们留下 print [=23=](在这种情况下与 print 相同)


考虑:

awk '{myvar="1"; print $myvar}' <<< "field#1 field#2 field#3"

在这种情况下 $myvar 变为 </code>,其中 <strong> 是 </strong> 一个有效的字段引用,因此生成的输出是:</p> <pre><code>field#1