1

I have a txt (ip.txt) file that contains IP addresess. I group them under TCP and UDP. File excerpt is below:

#TCP
162.298.38.930
162.298.38.931
162.298.38.932
#UDP
162.298.38.930
162.298.38.931
162.298.38.932

I have a specific IP (162.298.38.929) to add both by bash script into this ip.txt under TCP and UDP lines so it should like this.

#TCP
162.298.38.929
162.298.38.930
162.298.38.931
162.298.38.932
#UDP
162.298.38.929
162.298.38.930
162.298.38.931
162.298.38.932

How can I achieve this in bash script? Line number is not usable for my case because #TCP and #UDP line number can change because I add lots of comments into the file. Bash Script should search and add the IP both under TCP and UDP.

1 Answer 1

5

Use GNU Sed's Append Action

Assuming both sections have 162.298.38.932, and that you want to append the other IP address immediately below both entries, then the following sed script does the job.

sed '/162\.298\.38\.932/a\162.298.38.929' ip.txt
3
  • Thanks. I can see IP is added appropriately in terminal but when I check the file it does not have the changes saved. Any idea please? Commented Sep 3, 2014 at 3:52
  • @NecNecco If you want to edit the file in-place, rather than redirecting output to another file, then just add the --in-place flag when you call GNU sed. Commented Sep 3, 2014 at 3:56
  • now works perfectly Commented Sep 3, 2014 at 4:09

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.