Saturday, February 5, 2022

[SOLVED] Updating IP values after a specific string in a configuration file using SED

Issue

I'm trying to figure out how to replace some text in a config file even though I don't always know the full content.

For example:

[IP] 192.168.1.0

I want to change the IP value even though I may not know what it might be at the time.

I think SED is the way to do, but that only seems to deal with replacements where you know exactly what you are replacing:

 sed -i -e 's/few/asd/g' hello.txt

Is there a way I can match on the [IP] and switch out the line for a new one, even if I dont know what the value of the IP is?


Solution

Here is an example:

s="[IP] 192.168.1.0"
ip="192.168.15.24"
sed -i "s/^\[IP] .*/[IP] $ip/" hello.txt

See the online demo.

Here, ^\[IP] .* matches

  • ^ - start of a line
  • \[IP] - an [IP] substring
  • - a space
  • .* - any 0 or more characters.

If you want to use more specific matching pattern, consider chaning ^\[IP] .* to

^\[IP] [0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$

Or

^\[IP] [0-9]\{1,3\}\(\.[0-9]\{1,3\}\)\{3\}$

Here, [0-9]\{1,3\} matches 1, 2 or 3 digits, and \(\.[0-9]\{1,3\}\)\{3\} matches 3 repetitions of . and 1, 2 or 3 digits up to the end of a line ($).

Note that this "backslash hell" is due to the fact this regex is POSIX BRE compliant. To get rid of them, use a POSIX ERE regex by passing -E option:

sed -i -E "s/^\[IP] [0-9]{1,3}(\.[0-9]{1,3}){3}$/[IP] $ip/" hello.txt


Answered By - Wiktor Stribiżew
Answer Checked By - Katrina (WPSolving Volunteer)