【问题标题】:Combine lines in a text file of Linux server with condition [closed]将Linux服务器文本文件中的行与条件组合起来[关闭]
【发布时间】:2014-07-22 21:11:56
【问题描述】:

我在 Linux 服务器上的文本文件中有如下记录 -

telephone = 1111
a=1
b=2
telephone = 2222
a=1
b=2
c=3
telephone = 3333
a=1
b=2
c=3
d=4

我需要这样 -

telephone = 1111, a=1, b=2
telephone = 2222, a=1, b=2, c=3
telephone = 3333, a=1, b=2, c=3, d=4

Grep 或 perl 命令都可以,只要能帮助得到结果。

【问题讨论】:

  • 描述您的要求并要求某人为您编写代码、解释如何编写代码或提供示例或参考的问题是题外话。请确定有关编程的特定问题或问题。包括尝试的解决方案、结果与预期结果有何不同的解释,以及您收到的任何错误消息的全文。请阅读关于提出好问题的建议:[How to Ask]、[Writing the perfect question]。
  • 使用gnu awk awk 'NR>1 {$1=RS$1;print}' OFS=", " RS="telephone = " file

标签: linux perl grep


【解决方案1】:

使用 perl 单行:

perl -ne 'chomp; print !/^telephone/ ? ", " : $. > 1 ? "\n" : ""; print' file.txt

开关

  • -n:为输入文件中的每一行创建一个 while(<>){...} 循环。
  • -e:告诉perl 在命令行上执行代码。

【讨论】:

  • 这在最后错过了一个换行符。
【解决方案2】:

假设您在 input.txt 文件中有输入,请尝试以下操作:

perl -ne 'chomp; print /^telephone/ ? "\n$_" : ", $_" } { print "\n"' input.txt

编辑:防止在开头换行:

perl -ne 'chomp; print !/^telephone/ ? ", $_" : $. > 1 ? "\n$_" : "$_" } { print "\n"' input.txt

【讨论】:

  • 这会在开始时给出一个空行。
  • 谢谢,我已经编辑了答案以防止它发生。
【解决方案3】:

这也可以通过 awk 方便地完成:

awk 'NR == 1 { buf = $0; next } /^telephone/ { print buf; buf = $0; next } { buf = buf ", " $0 } END {print buf}' input.txt

这个单行可能可以进一步缩短,不过...

编辑:可以,考虑到 awk 从字符串构建布尔值的方式:

awk '/^telephone/ { if(buf) print buf; buf = $0; next } { buf = buf ", " $0 } END {print buf}' input.txt

EDIT2:我添加了我的 sed 解决方案,它不需要在 ooga 的解决方案中看到的肢体扭曲:

sed -f myscript input.txt

其中myscript如下:

#n
/^telephone/ {
  x
  s/\n/, /gp
  g
  n
  }
H
$ {
  g
  s/\n/, /gp
  }

【讨论】:

    【解决方案4】:

    即使sed 也可以做到这一点。

    sed '
      $ {H; b output}
      {
        s/telephone/&/
        t output
          H
          d
        : output
          x
          s/\n/, /g
      }
      1d
    ' file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      相关资源
      最近更新 更多