How to find a text, copy it and insert in next line in a file?
Solution 1
sed -E 's%<title>(.*)</title>%<title>\1</title>\n<desc>\1</desc>%g' file.xml
should do your homework.
To explain it a bit further:
-E
parameter tells sed
to use extended regular expressions, so you can use references. Replacing with sed is normally done in the form s/search/replace/g
. As there are slashes in the search text we use %
instead of /
for sed to mark the parts, so we do not have to mask the slashes in the search text by a backslash. The rest is normal regex stuff, \1
in the replace part references the snippet inside (…)
in the search part.
Solution 2
XML parsers/processors are the right tools for manipulating XML data.
xmlstarlet solution:
the exemplary input.xml
content:
<root>
some text
<title>text 1</title>
some text
<title>text 2</title>
some text </root>
xmlstarlet ed -a '//title' -t elem -n 'description' -v '' input.xml \
| xmlstarlet ed -u '//description' -x './preceding-sibling::title[1]/text()'
The output:
<?xml version="1.0"?>
<root>
some text
<title>text 1</title><description>text 1</description>
some text
<title>text 2</title><description>text 2</description>
some text </root>
ed
- edit mode-a
- append action-u
- update action
Related videos on Youtube
xjr
Updated on September 18, 2022Comments
-
xjr over 1 year
I'm trying to write a script that processes .xml file. It has to find all lines with a
<title>
element, copy it, and paste in a next line after that found one, but also changing the element type. Here is an example.Original:
some text
<title>
text 1</title>
some text
<title>
text 2</title>
some textAnd this is what I need to get:
some text
<title>
text 1</title>
<description>
text 1</description>
some text
<title>
text 2</title>
<description>
text 2</description>
some textCan it be done with sed or grep (or some other tool)?
-
RomanPerekhrest almost 7 yearswhy the second
<title>
line hastext 1
in the result? a typo?
-
-
countermode almost 7 yearsThis answer needs explanation.
-
xjr almost 7 yearsThank you, it works. I have not analyzed it yet, but it works!