【问题标题】:How to print specific columns from file using bash?如何使用 bash 从文件中打印特定列?
【发布时间】:2019-10-15 10:04:33
【问题描述】:

我有文件,其上下文如下:

               CA Services Status Report

           Component Name               Pid        Status
------------------------------------  -------  --------------
WAAE Web Server (ASD)                   20841  running
WAAE Application Server (ASD)           20281  running
WAAE Scheduler (ASD)                    20486  running
WAAE Agent (WA_AGENT)                   20109  running
CA-wcc-services Server                  22385  running
CA-wcc Server                           24410  running

我只想在屏幕上打印 Pid。

我尝试使用 awk 和 grep 但无法打印 Pid。

cat test | awk '{print $5}'

我只想打印 Pid 列,但无法准确打印。

【问题讨论】:

  • 您的列标签是分开的还是只是空格?

标签: shell awk grep


【解决方案1】:

您能否尝试以下操作(使用提供的样本进行测试)。

awk 'NF && !/Report/ && !/Status/ && !/^-/{print $(NF-1)}' Input_file

或者(根据詹姆斯先生的评论):

awk 'NF&&$(NF-1)~/[0-9]+/{print $(NF-1)}' Input_file

【讨论】:

  • $(NF-1) 是最好的。也许将其简化为:awk 'NF&&$(NF-1)~/[0-9]+/{print $(NF-1)}' file
  • 巧妙使用$(NF-1)++
  • @RavinderSingh 感谢您的意见。如果只需要显示第三列,即服务状态,请告诉我应该怎么做。就像跑步或不跑步一样。
【解决方案2】:

如果 pid 字段中只有数字,请提取数字:

$ awk 'match($0,/[0-9]+/){print substr($0,RSTART,RLENGTH)}' file
20841
20281
...

或者在记录 4 之后使用多个空格作为字段分隔符:

$ awk -F"  +" 'NR>=5{print $2}' file
20841
20281
...

【讨论】:

    【解决方案3】:

    你可以使用这个awk 假设文件只有空格并且数字可能出现在一行中的任何位置:

    awk '!n && n=index($0, " Pid "){++n} n{s=substr($0, n); sub(/ .*/, "", s); print s}' file
    

    Pid
    -----
    20841
    20281
    20486
    20109
    22385
    24410
    

    【讨论】:

      【解决方案4】:

      由于您似乎有一个固定的布局,只需测量事物的位置:

      <file tail +5 a.txt | cut -c41-45
      

      从第 5 行开始,只取第 41 到第 45 列的字符。与 AWK 相同(尽管我发现上面的内容更直观):

      awk 'NR>=5 { print substr($0, 41, 5) }' file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-30
        • 1970-01-01
        • 2013-10-26
        • 2021-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多