Home > OS >  add line to file if matched in sed regular expression
add line to file if matched in sed regular expression

Time:02-25

I want to check in a file if the word "range 192.168.1.1 192.168.1.100" , if the word range exists in the line then I want to add another line "ip address dhcp" that should be above the line "range 192.168.1.1 192.168.1.100" as a result such as :

"range 192.168.1.1 192.168.1.100" as a result i get : 
"ip address dhcp"
"range 192.168.1.1 192.168.1.100"

I tried with this regular expression: "sed -r /s/([[:space:]]*)/range/l\ip address dhcp" but did not work for me !

Thanks in advance

CodePudding user response:

Like this:

$ cat a.txt 
foo
bar
range 0000.00000 90000
baz

$ < a.txt sed '/range 0000\.00000 90000/i\ip address dhcp' 
foo
bar
ip address dhcp
range 0000.00000 90000
baz

CodePudding user response:

You can use either

sed -E '/range ([0-9]{1,3}\.){3}[0-9]{1,3}/i\ip address dhcp' file

Or, a bit more precise:

sed -E '/range ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)([^0-9]|$)/i\ip address dhcp' <<< "$s"

See the online demo.

See Validating IPv4 addresses with regexp for more IP address patterns if you need to adjust this pattern part.

Also, see the sed docs:

i\
text
insert text before a line.

  • Related