Extracting text from within a section of text using AWK

I have a command which returns the below output. How can I write a script to extract mainhost and secondhost from this output and put it into an array? I may sometimes have more hosts like thirdhost. I am redirecting this output to a variable. So I guess there should be a awk or sed command to extract it. But I am not able to figure it out.I am using the below command, which prints the secondhost.How can I change it to print mainhost as well.

echo $var | awk -F\" '{print $(NF-1)}'
{
    "outcome" => "success",
    "result" => [
        "mainhost",
        "secondhost"
    ]
}
$ awk -F\" '/"result"/ { getline; print $2; getline; print $2 }' file1
mainhost
secondhost

A variant of your original:

echo $var | awk -F\" '{print $(NF-1), $(NF-3)}'
1 Like

Thanks Scott for your quick reply. It works when I have mainhost and secondhost. Sometimes I will have more than two hosts like below. Its random and depends on the environment I am running. So how can I make it work whether it has 2 hosts or more.

{
    "outcome" => "success",
    "result" => [
        "mainhost",
        "secondhost"
        "thirdhost"
    ]
}
$ cat myScript
awk -F\" '/"result"/ { P=1; next }
  /]/ { P=0 }
  P { X=(X?X " " $2:$2) }
  END { print X }
' file1

$ cat file1
{
    "outcome" => "success",
    "result" => [
        "mainhost",
        "secondhost"
        "thirdhost"
    ]
}

$ ./myScript
mainhost secondhost thirdhost
1 Like

Thanks Scott! It works perfectly.

You're welcome!

If you're looking for your thread, I've renamed it to "Extracting text from within a section of text using AWK". "Scripting help" isn't very meaningful :slight_smile:

also, if any other formats of "results" in file1 like:

{
    "outcome" => "success",
    "result" => [ "mainhost", "secondhost", "thirdhost", "fourthost", "manyhosts" ]
}

try:

hosts=($(sed -n '/"result".*\[/,/\]/p' file1 | tr -d '\n' | sed 's/.*\[ *//;s/ *\].*//; s/ *, */ /g;'))
echo ${hosts[@]}
"mainhost" "secondhost" "thirdhost" "fourthost" "manyhosts"
1 Like

Nicely done :slight_smile: