0
  • Platform: RHEL7
  • Shell: Bash
  • Expected Result: store value as a variable

I'm trying to capture an IP from text that looks like this:

              {
                "ip": "12.34.56.7",
                "type": "LEARNED"
              }

When I run the following command from the terminal, I get the IP as expected.

grep '"ip":' ../path/to/file.txt | awk '{ print $2 }' | tr -d '"' | tr -d ','

Below is what I have in the script:

IP=grep '"ip":' ../path/to/file.txt | awk '{ print $2 }' | tr -d '"' | tr -d ','

I've tried a few different things, such as putting everything after IP= in quotes or escaping the quotes around the grep ip text with \\ but no dice. I'm just not sure of the right method of going about this. The script either breaks apart my command if it doesn't have quotes, or for some reason it drops the $2 from awk.

Thanks for any info.

muru
  • 69,900
  • 13
  • 192
  • 292
  • Are you dealing with a JSON document? What is the structure of that document (leading up to the keys whose values you want to extract)? – Kusalananda Aug 20 '21 at 15:43
  • 2
    Are you just asking [How can I assign the output of a command to a shell variable?](https://unix.stackexchange.com/questions/16024/how-can-i-assign-the-output-of-a-command-to-a-shell-variable) Regardless, you should probably be using something like `jq -r '.ip' ../path/to/file.txt` as the command if `file.txt` is actually a JSON document. – steeldriver Aug 20 '21 at 15:45

1 Answers1

0

When you want to assign the output of a shell command to a variable, use VAR=$(command), in your case

IP=$(grep '"ip":' ../path/to/file.txt | awk '{ print $2 }' | tr -d '"' | tr -d ',')

But some time ago somebody decided to invent sed to avoid too much complicated piping:

IP=$(sed '/"ip":/!d;s/",//;s/.*"//' ../path/to/file.txt)
  • /"ip":/!d ignores all lines without "ip": in it
  • s/",// removes the trailing double quote and comma
  • ;s/.*"// removes everything upto the remaining double quote
Philippos
  • 13,237
  • 2
  • 37
  • 76
  • 1
    Note that you may combine all of this pipeline into a single `awk` expression, `awk '/"ip":/ { gsub("[\",]","",$2); print $2 }'` (or something), and that it would be better to use a JSON parser, such as `jq` to parse JSON, especially if you need to do conditional parsing and decoding of the data. – Kusalananda Aug 20 '21 at 15:58
  • No matter whether you use `awk` or `sed`, just don't do too much confusing piping (-: – Philippos Aug 20 '21 at 16:02