search for string and add the second line below

Hi there, i have an /etc/hosts file that is organised in sections, like this

#
# Oracle Servers
#
1.1.1.1  boxa
2.2.2.2  boxb
9.9.9.9  boxj

#
# Prod Sybase Servers
#
6.6.6.6  boxt
4.4.4.4 boxz

I am just trying to write a line of code that will ill be able to pass the comment block name without the prepended hash and space (e.g. just ' Prod Sybase Servers') and it would add the new host entry at the top of the block under the last comment hash

Ive managed to put together a little awk line that will take a string to search in the first column ($1) and place the new entry directly below it,

 nawk -v entry="5.5.5.5 boxy" -v string='6.6.6.6' '{if ($1==string) {print $0"\n"entry} else {print $0}}' /etc/hosts

This code will place my new entry below the '6.6.6.6 boxt' entry (or any other string that I search in the first column). This would work fine if i always knew an IP address in the file to search for, but in reality, we would like to define the comment block to add to as this will always be consistent. The downside is that it will have a variable amount of columns

Whist having the issue of trying to define the columns that need searching, I also have the issue of getting it to appear underneath the single hash that will always be directly below the search string. (so I want it to appear on the line after the next line down)

so for example if i provided a search string of 'Prod Sybase Servers' and a new entry of '5.5.5.5 boxy' then i would want it to look like this (based on the above example file)

#
# Oracle Servers
#
1.1.1.1  boxa
2.2.2.2  boxb
9.9.9.9  boxj

#
# Prod Sybase Servers
#
5.5.5.5 boxy
6.6.6.6  boxt
4.4.4.4 boxz

Any help or advice on how i could tackle this one would be greatly appreciated

Hi

awk -v srch="^# Prod Sybase" -v line="1.1.1.1 blah" '{ if (match($0,srch)) { print; getline; print; print line; } else print }' /etc/hosts

Straight forward way would be..

awk -v ent='5.45.4.5' -v str='Prod Sybase Servers' -v nl='\n' '$0~str{c=$0;getline;print c nl $0 nl ent;next}1' inputfile

thanks for your help guys :slight_smile: