-1

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Jimmy
  • 12,087
  • 28
  • 102
  • 192
  • 1
    In `s/pattern/replacement/`, pattern can match arbitrary regular expressions rather than fixed strings. – William Pursell Jun 03 '19 at 15:54
  • 2
    Just use: `sed 's/\[IP\] .*/replacement/' file` – anubhava Jun 03 '19 at 15:55
  • Easier with awk without regex: `awk -v repl="$newip" '$1=="[IP]"{$2 = repl} 1' file` – anubhava Jun 03 '19 at 15:57
  • 2
    Possible duplicate of [sed wildcard substitution](https://stackoverflow.com/q/6258643/608639), [Using SED with wildcard](https://stackoverflow.com/q/9189120/608639), [sed wildcard search replace](https://stackoverflow.com/q/5843870/608639) – jww Jun 03 '19 at 16:13

1 Answers1

0

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Just FYI, a [regex for IP matching in `grep`](https://stackoverflow.com/questions/11482951/extracting-ip-address-from-a-line-from-ifconfig-output-with-grep). – Wiktor Stribiżew Jun 03 '19 at 16:00