2

I am having this scenario and need if I can improvise the awk output.

  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. I am looking to cut the pattern after /virtualMachines/

  3. Hence, used the below awk command to get the output.

    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
    
  4. Is there any way I can use some options like 'getline' or multiple awk options in single awk execution or better ways to improve the command to get the output?

Please suggest.

2
  • Good that you have shown your efforts in post, please try to select an answer(after you see some answers in your post) as a correct answer too to complete the thread. Commented Jun 15, 2018 at 4:04
  • 1
    If this is JSON I suggest to use jq.
    – Cyrus
    Commented Jun 15, 2018 at 4:21

3 Answers 3

3

Use " and / as field separators and print second last field:

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

Output:

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

If the spacing of example.txt is as consistent as it seems, then it's simpler to use cut with the -characters count option:

cut -c 127-162 example.txt

Output:

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

You could also use sed for this:

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

Matches anything .* forwardslash / then captures \( any number of non-forwardslash characters [^/]*, ends the capture \) followed by a quote & comma to end ",, and replaces this with the captured group (anything between the forwardslash and the ", at the end.

Not the answer you're looking for? Browse other questions tagged or ask your own question.