zoukankan      html  css  js  c++  java
  • 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.


    给懒得看英文的人翻译一下:
    $0精确的表示你从awk输入中读到的一条记录。它包含了开头和结尾的空格及分割字段间的空格(或其它字符)
    这里有一个很不寻常的错误会发生,当你通过FS或OFS改变了记录的分隔符时,而你正好想用print或print $0打印出这条记录,但是
    它不会如你所愿的(正如我们上面的例子),因为这条记录没有任何改变,所以你要强制改变这条记录,方法就是 $1=$1或$2=$2或随便你想改变什么变量。

    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

  • 相关阅读:
    Luogu P4053 [JSOI2007]建筑抢修
    CF894E Ralph and Mushrooms
    Boruvka
    Codeforces Beta Round #25 (Div. 2 Only) C. Roads in Berland
    HDU 3714/UVA1476 Error Curves
    HDU 5410 CRB and His Birthday
    HDU 1796 How many integers can you find
    UVA 11624 Fire!
    POJ 3279 Dungeon Master
    POJ 1321 棋盘问题
  • 原文地址:https://www.cnblogs.com/txwsqk/p/3233421.html
Copyright © 2011-2022 走看看