Adding XML element in XML file using sed command in shell script
You cannot have an unescaped newline in sed replacement text, that is $CONTENT
in your example. sed uses the newline just like the shell does, to terminate a command.
If you need a newline in the replacement text, you need to precede it with a backslash.
There is another way to add text using the r
option. For example:
Lets say your main file is;
$ cat file<Students> <student> <name>john</> <id>123</id> </student> <student> <name>mike</name> <id>234</id> </student></Students>
You text you want to add is in another file (not variable):
$ cat add.txt <student> <name>NewName</name> <id>NewID</id> </student>
You can do (using gnu sed
):
$ sed '/<\/Students>/{ r add.txt a \</Students> d }' file<Students> <student> <name>john</> <id>123</id> </student> <student> <name>mike</name> <id>234</id> </student> <student> <name>NewName</name> <id>NewID</id> </student></Students>
However, having given this option, it is still a very bad idea to parse xml with regular expression. It makes the solution very fragile and easy to break. Consider this as a learning exercise only.