Ignoring the fact that you are using line-oriented tools for editing data that is clearly not oriented in lines but as XML...
To insert the string <!--
in front of any line that contains the string Deep
, use sed
like so:
sed '/Deep/ s/^/<!--/' file.xml >newfile.xml
There is no need to first calculate the line numbers with grep
or any other tools, as far as I can see.
Would you want to insert the <!--
string at the start of the line above whatever lines contain Deep
, then use
sed -e '1 { h; d; }' -e '/Deep/ { x; s/^/<!--/; x; }' -e x -e '$ { p; x; }' file.xml >newfile.xml
Or, if the file will fit easily in memory, script the ed
editor (this may actually be the most flexible approach):
printf '%s\n' 'g/Deep/-1 s/^/<!--/' 'w newfile.xml' 'q' | ed -s file.xml
sed (GNU sed) 4.2.2
. No exception, and does the edit (obviously I changed LineNum to 3 for my test). Is it possible there is an invisible character (like '\r') after the...205
? – Paul_Pedant Mar 10 '21 at 16:36bash -x
and runLC_ALL=C sed -n l < the-script
to spot invisible characters in it. – Stéphane Chazelas Mar 10 '21 at 16:53