【问题标题】:processing alternate line bash处理换行 bash
【发布时间】:2012-06-05 05:53:25
【问题描述】:

我有一个这样的文件

line1
this is line1
line2
this is line2
line3
this is line3

我想使用 awk 或 sed 来删除每个交替行的尾随换行符,以便像这样合并它们

line1: this is line1    
line2: this is line2
line3: this is line3

如何使用 awk 或 sed 进行操作

【问题讨论】:

    标签: sed awk


    【解决方案1】:
    $ cat input 
    line1
    this is line1
    line2
    this is line2
    line3
    this is line3
    $ awk 'NR%2==1 {prev=$0} NR%2==0 {print prev ": " $0} END {if (NR%2==1) {print $0 ":"}}' input
    line1: this is line1
    line2: this is line2
    line3: this is line3
    $ 
    

    【讨论】:

    • 这应该可以防止消失:awk 'NR%2==1 {prev=$0} NR%2==0 {print prev ": " $0} END {if (NR%2==1) {print $0 ":"}}' input(顺便说一下,不需要重定向)。
    • @Dennis:谢谢!这比我预期的要好。
    【解决方案2】:

    使用sed:

    sed -n '${s/$/:/p};N;s/\n/: /p' inputFile
    

    对于带有原始文件备份的就地编辑,

    sed -n -i~ '${s/$/:/p};N;s/\n/: /p' inputFile
    

    【讨论】:

    • 这应该可以防止消失:sed -n '$p;N;s/\n/: /p'sed -n '${s/$/:/;p};N;s/\n/: /p'
    【解决方案3】:

    这可能对你有用:

    sed -i '$!N;s/\n/: /' file
    

    【讨论】:

      【解决方案4】:
      sed 's/^\(line.*\)/\1:/' filename | paste - -
      

      还有 Perl 类似物:

      perl -ape 's/^(line.+)\n/$1: /' filename
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-29
        • 2015-11-25
        • 2010-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-03
        相关资源
        最近更新 更多