Don't use sed to manipulate XML documents.
There are good tools for that activity.
xmlstarlet is one of them.
A valid XML structure requires a root element at the top of the node tree.
Let's say we have an XML fragment (test.xml
):
<root>
<Name>title firstname lastname</Name>
<Home>+49 (30) 1234 94</Home>
<Mobile>+49 (171) 1234 94</Mobile>
<Name>title firstname lastname</Name>
<Home>+49 (30) 1234 94</Home>
<Mobile>+49 (171) 1234 94</Mobile>
</root>
The command:
xmlstarlet ed -u "//Home|//Mobile" -x "translate(normalize-space(.),'() ','')" test.xml
Details:
ed
- enables edit mode
-u
- to update xml structure
"//Home|//Mobile"
- xpath expression to select the needed elements
-x
- to update the needed values with xpath expression
.
(period) - points to the current selected node(s)
normalize-space()
- the function which returns the argument string with whitespace normalized by stripping leading and trailing whitespace and replacing sequences of whitespace characters by a single space
translate(string, string, string)
- the function which returns the first argument string with occurrences of characters in the second argument string replaced by the character at the corresponding position in the third argument string.
The output:
<?xml version="1.0"?>
<root>
<Name>title firstname lastname</Name>
<Home>+4930123494</Home>
<Mobile>+49171123494</Mobile>
<Name>title firstname lastname</Name>
<Home>+4930123494</Home>
<Mobile>+49171123494</Mobile>
</root>