Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add string between two patterns - sed

Tags:

linux

bash

sed

I'm looking to build a startup script that will add a string of text between two patterns.

8.34.217.13 cds.rhel.updates.googlecloud.com
10.128.0.2 instance-1.c.testenvio1.internal instance-1 **want to add string here** # Added by Google
169.254.169.254 metadata.google.internal  # Added by Google

I want it to look like this:

8.34.217.13 cds.rhel.updates.googlecloud.com
10.128.0.2 instance-1.c.testenvio1.internal instance-1 104.197.247.254 instance1.com  # Added by Google
169.254.169.254 metadata.google.internal  # Added by Google

I'm using the following sed command but it inserts my string when it encounters the first "instance-1"

sed -i 's/\<instance-1\>/& 104.197.247.254 instance1.com/' /etc/hosts


8.34.217.13 cds.rhel.updates.googlecloud.com
10.128.0.2 instance-1 104.197.247.254 instance1.com.c.testenvio1.internal instance-1  # Added by Google
169.254.169.254 metadata.google.internal  # Added by Google
like image 808
glux Avatar asked Mar 11 '26 23:03

glux


1 Answers

Perhaps some insight about where the data is coming from is certainly helpful here.

The # Added by Google suggests that those lines contain information about Google Compute Engine instances. More importantly, they are lines added by Google and fortunately follows a predefined pattern.

In that case, something like below would help

$ sed -Ei -- 's/([[:blank:]]+instance-1[[:blank:]]+)(#.*)$/\1 104.197.247.254 instance1.com \2/' /etc/hosts

Output

8.34.217.13 cds.rhel.updates.googlecloud.com
10.128.0.2-instance-1-c.testenvio1.internal instance-1   104.197.247.254 instance1.com # Added by Google
169.254.169.254 metadata.google.internal  # Added by Google

Sidenote: The actual number of spaces are preserved too.

like image 123
sjsam Avatar answered Mar 14 '26 01:03

sjsam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!