如何使用awk剪切一行中的最后一个字段进行文本处理?

时间:2018-06-15 03:59:57

标签: bash shell unix awk

我有这个场景,如果我可以即兴创作awk输出则需要。

  1. cat example.txt

    "id": "/subscriptions/fbfa3437-c63c-4ed7-b9d3-fe595221950d/resourceGroups/rg-ooty/providers/Microsoft.Compute/virtualMachines/fb11b768-4d9f-4e83-b7dc-ee677f496fc9",
    "id": "/subscriptions/fbfa3437-c63c-4ed7-b9d3-fe595221950d/resourceGroups/rg-ooty/providers/Microsoft.Compute/virtualMachines/fbee83e8-a84a-4b22-8197-fc9cc924801f",
    "id": "/subscriptions/fbfa3437-c63c-4ed7-b9d3-fe595221950d/resourceGroups/rg-ooty/providers/Microsoft.Compute/virtualMachines/fc224f83-57f4-41eb-aee3-78f18d055704",
    
  2. 我希望在/ virtualMachines /

  3. 之后剪切模式
  4. 因此,使用下面的awk命令获取输出。

    cat example.txt | awk '{print $2}' | awk -F"/" '{print $(NF)}' | awk -F'",' '{print $1}'
    fb11b768-4d9f-4e83-b7dc-ee677f496fc9
    fbee83e8-a84a-4b22-8197-fc9cc924801f
    fc224f83-57f4-41eb-aee3-78f18d055704
    
  5. 我有什么方法可以使用像' getline'或单个awk执行中的多个awk选项或更好的方法来改进命令以获得输出?

  6. 请建议。

3 个答案:

答案 0 :(得分:3)

使用"/作为字段分隔符并打印倒数第二个字段:

awk -F '["/]' '{print $(NF-1)}' file

输出:

fb11b768-4d9f-4e83-b7dc-ee677f496fc9
fbee83e8-a84a-4b22-8197-fc9cc924801f
fc224f83-57f4-41eb-aee3-78f18d055704

答案 1 :(得分:1)

如果 example.txt 的间距与看起来一致,那么cut haracters <{1}}的使用情况就更简单了/ em>计数选项:

-c

输出:

cut -c 127-162 example.txt

答案 2 :(得分:0)

您也可以使用sed:

sed 's#.*/\([^/]*\)",#\1#' example.txt

匹配任何.* forwardslash /然后捕获\(任意数量的非转发字符[^/]*,结束捕获\)后跟引号&amp;逗号结束",,并将其替换为捕获的组(结尾处的前锋和",之间的任何内容。