Say I want to automatically update my /etc/ntp.conf configuration using sed. Format of ntp.conf allows to define lists by usage same keywords for lines occurred all over the file. For example:# first block occurrencesserver 1.1.1.1server 2.2.2.2driftfile /var/lib/ntp/drift# second block of occurrencesserver 3.3.3.3server 4.4.4.4Now, I've got updated list of ntp servers, say 5.5.5.5, 6.6.6.6 and 7.7.7.7. As a result I want to get:# first block occurrencesserver 5.5.5.5server 6.6.6.6server 7.7.7.7driftfile /var/lib/ntp/drift# second block of occurrencesCan I do it with sed? Is it right tool for this problem or should I use something else?P.S.: commenting out second block (or both) of occurrences could also be an option.
sed: remove all matches in the file and insert some lines where the first match was
text processing;sed;configuration;ntpd
If you have the new list of servers in a file named list.txt in cwd:sed '/^server/{x;//!r list.txtd}' /etc/ntp.confor, if you don't want to use a file but rather hardcode the new server names:sed '/^server/{x;//!c\server 1\........\server n-1\server nd}' /etc/ntp.confThis assumes that there is at least one non-commented server line in your /etc/ntp.conf (also, it will not remove any server lines that are commented out - you can change the regex to include those too). If you wanted to insert those lines even if there were no server entries in original file (and in that case, add the new servers at the end of file) you could do something like:sed '/^server/{x;//!r list.txtd}${x;//!r list.txtx}' /etc/ntp.confor use the same conditions if you prefer using c\ - I'll leave that as an exercise. Keep in mind that when changing lines with c\ all backslashes and embedded newlines have to be escaped with a backslash (as in my example).  