zoukankan      html  css  js  c++  java
  • awkOFS问题

    awk改变了OFS,$0却没变化
    一个文件1.txt,内容如下

    a
    b
    c
    d
    e
    

      


    目的把列变行,输出为: a b c d e

    脚本如下:

    awk 'BEGIN{RS="";FS="
    ";OFS=" "}{print }' test
    a
    b
    c
    d
    e
    

      


    理论上应该实现我们想要的 a b c d e

    问题出在这里

    Understanding $0


    It is important to remember that $0 is the full record, exactly as it was read from the input. This includes any leading or trailing whitespace, and the exact whitespace (or other characters) that separate the fields.

    It is a not-uncommon error to try to change the field separators in a record simply by setting FS and OFS, and then expecting a plain ‘print’ or ‘print $0’ to print the modified record.

    But this does not work, since nothing was done to change the record itself. Instead, you must force the record to be rebuilt, typically with a statement such as ‘$1 = $1’, as described earlier.


    google翻译:

    重要的是要记住,$ 0是完整的记录,与从输入读取完全一样。 这包括任何前导或尾随空白以及分隔字段的确切空格(或其他字符)。
    尝试通过设置FS和OFS来更改记录中的字段分隔符是常见的错误,然后期待一个普通的“打印”或“打印$ 0”来打印修改的记录。
    但是这并不奏效,因为没有改变记录本身。 相反,您必须强制重新创建记录,通常使用诸如“$ 1 = $ 1”的语句,如前所述。

    It works !

    quke@Raphaelqu:/tmp$ awk 'BEGIN{RS="";FS=" ";OFS=" "}{$1=$1;print}' 1.txt
    a b c d e f g

    详情参考:
    http://www.gnu.org/software/gawk/manual/html_node/Changing-Fields.html

  • 相关阅读:
    linux办公软件的使用和病毒防范
    需要了解的基本礼仪素养
    遗留问题
    shell基本命令
    shell编程
    遇到过得问题
    mac电脑操作
    Linux编程
    BZOJ 1601 [Usaco2008 Oct]灌水 (建图+mst)
    BZOJ 2653 middle (可持久化线段树+中位数+线段树维护最大子序和)
  • 原文地址:https://www.cnblogs.com/irockcode/p/7055016.html
Copyright © 2011-2022 走看看