【问题标题】:replace the last third line of a file using awk and sed使用 awk 和 sed 替换文件的最后第三行
【发布时间】:2013-11-17 10:48:04
【问题描述】:

我需要找到文件的最后第三行,如果是“}”,我应该用“}”替换它

我在想 awksed 这会找到文件的最后第三行

 PATTERN=$(awk '{v[c++]=$0}END{print v[c-3]}' $file)

我想用

 sed -i 's/$PATTERN/}/' $file

但这是错误的 不知道怎么继续

【问题讨论】:

    标签: sed awk


    【解决方案1】:

    这个awk 应该这样做(最后第三行more 已清除)

    cat file
    one
    two },
    three
    four
    more }, test }, hi
    five },
    yes
    

    awk '{v[++c]=$0}END {for (i=1;i<=NR;i++) {if (v[c-3]~"},") gsub(/},/,"}",v[c-3]);print v[i]}}' t
    one
    two },
    three
    four
    more }, test }, hi
    five },
    yes
    

    【讨论】:

    • @Jotn但文件保持不变
    • 要更改原始文件,请执行以下操作:awk (some commands) file &gt; tmp &amp;&amp; mv tmp file 这会将更改写回file
    • 有些事情是错误的,你也可以在你的例子中看到,文件的第一行丢失了!
    • 好收获。我刚刚复制了原始文件,它在使用后具有c++ 增量变量,因此数组将从0 开始,更改为++c PS,唯一使用单个命令的解决方案awk :)跨度>
    【解决方案2】:

    我需要找到文件的最后第三行,如果是“}”,我应该 用“}”替换它

    使用tacsed

    tac filename | sed '3s/^};$/}/' | tac
    

    在 MacOS 上,您可以说:

    sed '1!G;h;$!d' filename | sed '3s/^};$/}/' | sed '1!G;h;$!d'
    

    【讨论】:

    • 我在 mac 上运行,bash 抱怨找不到 tac 命令
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 2016-10-30
    • 2016-10-29
    • 1970-01-01
    • 2023-02-02
    相关资源
    最近更新 更多