Need bash script to use a sed command as a variable

I need to be able to use a sed command as a variable in a bash script. I have the sed command that almost works the way I want it. the command is

sed -n '/inet/,/}/p' config.boot

This gets me this result:

inet 192.168.1.245
        }

I need to get the IP address into a variable so I can use it. How do I use sed to strip off the inet and the }.

How does the command need to be changed to get this to work?

Thanks

ip=$(sed -n '/inet/,/}/{/inet/{s/inet *//;{p;q}}}' config.boot)

Thank you ! That works perfectly

Could be simplified as you want to quit after the first ip encountered:

ip=$(sed -n '/inet */ {s///; p; q}' file)
1 Like

Note that with standard sed (non-GNU) there needs to be a ; before the trailing } :

ip=$(sed -n '/inet */{s///p;q;}' config.boot)

or we can avoid the braces by using negation style:

ip=$(sed '/inet */!d; s///; q' config.boot)

--
Alternatively we can avoid the sub shell / external command altogether with just standard shell:

until [ "$inet" = inet ]; do
  read inet ip
done < config.boot

--
Note also that these are all naive approaches without knowing what the format of config.boot looks like. Also, if the are more inet configs in the same file, these will only pick the first one indiscriminately.

As a professional you should expect the unexpected.
What happens if the read fails or the "inet" is not found?
The following ends the loop if the read fails.

while
  read inet ip &&
  [ "$inet" != inet ]
do
  :
done < config.boot
1 Like

Yes that was indeed not a good approach. Also a good thing you pointed out that the shell approach only gives a proper answer if inet is present in the file. But this would still not solve that issue.

This may be more appropriate:

while read key value; do
  if [ "$key" = inet ]; then
    ip=$value
  fi
done < config.boot

There could be multiple inet entries I suppose, here is the format of the section of config.boot where it would be found

 static-host-mapping {
        host-name Nimbuslocal.net {
            alias phonesystem
            inet 207.148.13.85
        }
    }

I also have another section of the same file I need the IP from. Initially I thought I could adapt what you guys suggest to it, maybe not

group {
        address-group FailoverSystem {
            address 207.148.13.85
            description "Failover System IP Address"
        }

This would key on the name FailoverSystem

Thanks guys

fo_ip=$(sed -n '/FailoverSystem/,/}/{/^ *address /{s/ *address *//;{p;q}}}' config.boot)
echo "$fo_ip"
1 Like

Thanks rdrtxl that worked perfectly!