首页 > 解决方案 > 如何使用 grep 提取第三列?

问题描述

如何使用grep仅获取第三级 ID?

"id": 2,
      "id": 12,
          "id": 136,
          "id": 229,
          "id": 230,
          "id": 231,
          "id": 232,
          "id": 233,
          "id": 234,

我只想得到:

136
229
230
231
232
233
234

我用 grep 和 cut 尝试了不同的方法。

标签: linuxbashshellawkgrep

解决方案


使用 awk 提取数值(因为$NF+0要删除逗号):

$ awk '/^ {10}/{print $NF+0}' file

输出:

136
229
230
...

解释:

$ awk '
/^ {10}/ {        # records started by (at least) 10 spaces
    print $NF+0   # print the numeric value from the last field
}' file

如果值不是数字或有 4 级 ID,则需要调整:

$ awk '
/^ {10}[^ ]/ {     # starts with exactly 10 spaces
    sub(/,$/,"")   # remove comma from the end
    print $NF      # output last awk default defined field
}' file

推荐阅读