【问题标题】:Formatting text output in Bash在 Bash 中格式化文本输出
【发布时间】:2016-11-03 15:18:55
【问题描述】:

我有一些来自 pdsh 的输出,我想将其格式化以加载到数据库中。我需要它在 3 列中,并且本质上希望模块 ID 和消息在一行中。波纹管是我的输出:

10.125.45.58,scope, Module ID     = server-1
10.125.45.58,scope, Message       = Correctable memory error
10.125.45.58,scope, Module ID     = server-2
10.125.45.58,scope, Message       = Correctable memory error 

这是我需要的输出:

10.125.45.58,scope,server-1 Correctable memory error
10.125.45.58,scope,server-2 Correctable memory error

我一直在 awking 和 seding...我想不出任何想法?

这是我到目前为止所做的

cat myfile.txt | sed -e "s/:/\,scope\,/g" | grep -E '(Module ID|Message)'

谢谢。

【问题讨论】:

  • 你能把awk和sed发到现在吗?
  • 嘿,谢谢...我没有任何工作甚至关闭,我已经格式化了 pdsh 的 origanl 输出... # cat myfile.txt | sed -e "s/:/\,范围\,/g" | grep -E '(模块 ID|消息)'.

标签: linux bash awk sed formatting


【解决方案1】:
$ cat ip.txt 
10.125.45.58,scope, Module ID     = server-1
10.125.45.58,scope, Message       = Correctable memory error
10.125.45.58,scope, Module ID     = server-2
10.125.45.58,scope, Message       = Correctable memory error 

$ sed 'N; s/\n.*=//; s/ *Module ID.*= *//' ip.txt 
10.125.45.58,scope,server-1 Correctable memory error
10.125.45.58,scope,server-2 Correctable memory error 
  • N 获取下一行,因此替换适用于一起考虑的每两行
  • s/\n.*=//; 从换行符删除到最后一个 =
  • s/ *Module ID.*= *// 然后删除从 Module ID 到 = 的所有内容,周围有可选空格

【讨论】:

    【解决方案2】:

    sed 用于单行的简单替换,仅此而已。对于其他任何事情,您应该使用 awk 来实现可移植性、效率、简单性、清晰性、可维护性以及软件的大多数其他理想属性:

    $ awk 'NR%2{srvr=$NF;next} {ip=$1; sub(/.*=/,""); print ip srvr $0}' file
    10.125.45.58,scope,server-1 Correctable memory error
    10.125.45.58,scope,server-2 Correctable memory error
    

    【讨论】:

      猜你喜欢
      • 2014-06-07
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多