linux - 将新行更改为所选行的空格

标签 linux bash shell

我有一个文件,其输入如下:

Application handle                         = 36768
  ID of agent holding lock                 = 36433
Application handle                         = 36807
  ID of agent holding lock                 = 53074
Application handle                         = 52994
Application handle                         = 36433
Application handle                         = 36581
  ID of agent holding lock                 = 36580
Application handle                         = 36458

但我想要以下格式的输出:

Application handle                         = 36768  ID of agent holding lock                 = 36433
Application handle                         = 36807  ID of agent holding lock                 = 53074
Application handle                         = 52994
Application handle                         = 36433
Application handle                         = 36581  ID of agent holding lock                 = 36580
Application handle                         = 36458

最佳答案

这个 awk 的工作原理:

awk '$1 == "Application"{if (l) print l; l=$0; next}
     {l=l $0; next} END {print l}' file

Application handle                         = 36768  ID of agent holding lock                 = 36433
Application handle                         = 36807  ID of agent holding lock                 = 53074
Application handle                         = 52994
Application handle                         = 36433
Application handle                         = 36581  ID of agent holding lock                 = 36580
Application handle                         = 36458

说明:

这个 awk 首先评估这个条件:

  • $1 == "Application" 检查一行是否以 "Application" 开头。 如果条件匹配,那么它首先执行此操作
    • if (l) print l; 打印 l 的值 if l 不为 null
    • 然后设置l=$0,将变量l的值设置为$0(整行)
    • 最后调用 next 使 awk 移动到下一条记录
  • 然后,仅当 $1 != "Application"(要连接的行)时才计算第二个 {...}
  • 该 block 是{l=l $0; next} 将第二行附加到变量 l 调用 next
  • 这个循环一直持续到最后一行,最后
  • END {print l} 被调用以打印最后一行。

关于linux - 将新行更改为所选行的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20397131/

相关文章:

linux - 为什么程序头是可执行的?

linux - 仅在尚未运行时运行 cron 作业

bash - 在后缀文件中查找和替换 URL - Linux/Ubuntu

linux - 无法在 Gnome 中禁用 PrintScreen 键

linux - 创建共享库链接器 undefined reference

linux - shell脚本中调试函数的含义

python - grep 特定时间范围内的日志文件

bash - 现实生活中的 SHELL SCRIPTS 用法?

linux - 如何用 sed 替换 1 个文件中的所有匹配项?

作为 cron 作业失败的 Ruby 脚本