代码之家  ›  专栏  ›  技术社区  ›  Ritwik Bose

awk不会打印新行字符

  •  2
  • Ritwik Bose  · 技术社区  · 15 年前

    我正在使用下面的代码来更改现有的awk脚本,这样我就可以用一个简单的命令添加越来越多的案例。

    echo `awk '{if(/#append1/){print "pref'"$1"'=0\n" $0 "\n"} else{print $0 "\n"}}' tf.a
    

    请注意,第一次打印是 "pref'"$1"'=0\n" 所以它指的是变量 $1 awk 它本身

    ./tfb.a "c" 应将代码更改为:

    BEGIN{
    #append1
    }
    ...
    

    致:

    BEGIN{
    prefc=0
    #append1
    }
    ...
    

    有人知道这是为什么吗?

    2 回复  |  直到 15 年前
        1
  •  2
  •   Gordon Broom    15 年前

    如果你 awk 从方程中你可以看到发生了什么:

    # Use a small test file instead of an awk script
    $ cat xxx
    hello
    there
    $ echo `cat xxx`
    hello there
    $ echo "`cat xxx`"
    hello
    there
    $ echo "$(cat xxx)"
    hello
    there
    $
    

    backtick操作符过早地将输出扩展为shell“words”。你可以和我一起玩 $IFS shell中的变量(yikes),也可以只使用双引号。

    如果你在经营一家现代化的 sh (例如。 ksh bash ),您也可以使用 $() 语法(更容易找到匹配的开始/结束分隔符)。

        2
  •  2
  •   ghostdog74    15 年前

    像这样做。使用-v将变量从shell正确地传递给awk

    #!/bin/bash
    toinsert="$1"
    awk -v toinsert=$toinsert '
    /#append1/{
        $0="pref"toinsert"=0\n"$0
    }
    {print}
    ' file > temp
    mv temp file
    

    输出

    $ cat file
    BEGIN{
    #append1
    }
    
    $ ./shell.sh c
    BEGIN{
    prefc=0
    #append1
    }