-1

I have the following two files test.txt and test1.txt. I want to update the data of test.txt in to test1.txt under abc.com, however, first it has to remove the existing data so final output looks like test1.txt under output file section

test.txt

10.100.4.10
10.100.4.11
10.100.4.12

test1.txt

[abc.com]
10.100.44.10
10.100.44.11

[xyz.com]
10.100.55.10
10.100.55.11

[etc..]

OUTPUT FILE

test1.txt

[abc.com]
10.100.4.10
10.100.4.11
10.100.4.12

[xyz.com]
10.100.55.10
10.100.55.11
Inian
  • 62,560
  • 7
  • 92
  • 110
  • The goal is that you add some code (to your question) of your own to show at least the research effort you made to solve this yourself. – Cyrus Dec 19 '17 at 06:56
  • Have a look at this link, it points to the right direction : https://unix.stackexchange.com/questions/32908/how-to-insert-the-content-of-a-file-into-another-file-before-a-pattern-marker – kvantour Dec 19 '17 at 07:00

1 Answers1

0

If you know the address abc.com beforehand and that the entries are separated by a blank line then use the following sed commands. First one deletes the lines between abc.com and the first blank line and the second inserts the text you want from test1.txt.

$ sed '/^\[abc\.com\]/,/^$/{/^\[abc\.com\]/!{/^$/!d}}' test.txt | sed '/^\[abc.com\]/r test1.txt'
[abc.com]
10.100.4.10
10.100.4.11
10.100.4.12

[xyz.com]
10.100.55.10
10.100.55.11
SigmaPiEpsilon
  • 638
  • 5
  • 14
  • Now, if i run manually below command its working. However, in script when i called the domain name and file its not working. /bin/sed -i '/\babc.com/,/^$/{/^[0-9]/d};/\babc.com/r test.txt' /tmp/test1.txt Below is the call in the bash script. I tried to echo following command with the value and its taking correct value. What went wrong. /bin/sed -i '/\b$dmname/,/^$/{/^[0-9]/d};/\b"$dmname"/r $file' /tmp/test1.txt – user213618 Dec 20 '17 at 05:30
  • solved. used below in bash script /bin/sed -i "/\b$dmname/,/^$/{/^[0-9]/d};/\b"$dmname"/r $file" /tmp/test1.txt – user213618 Dec 20 '17 at 06:11
  • Yes if you want bash variable expansion you have to use double quotes. I also see you are using a different deletion criteria. If all the lines you need to delete begins with a number it is fine, but if there is any whitespace before the numbers it will be skipped – SigmaPiEpsilon Dec 20 '17 at 15:48