-2

I have code which will replace the xml tag at a particular line number

 LineNum=`grep -n "Deep" file.xml | cut -d: -f 1 | awk -F '[\t]' '{$NF = $NF -1;}1'`
    sed "${LineNum}s#^<Deep>#<!--<Deep>#" file.xml

While executing the command i am getting below exception

sed -e  expression  #1, char 7: unknown command `'

Can anyone provide me the solution for this?

2 Answers2

0

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
Kusalananda
  • 333,661
  • This printf '%s\n' 'g/Deep/-1 s/^/<!--/' 'w newfile.xml' 'q' | ed -s file.xml works perfectly if i want to insert the at the 36 the line after the pattern matching at the end of the tag so the output looks like -->. I am using the code printf '%s\n' 'g/Deep/+36 s/$/-->/' 'w newfile.xml' 'q' | ed -s file.xml. But it is not giving the desired output. – DEEP MUKHERJEE Mar 11 '21 at 02:49
  • @DEEPMUKHERJEE You question only concerned adding <!--. Conisder updating your question if you have other requirements. – Kusalananda Mar 12 '21 at 20:23
-2

does this help?

LineNum=$(grep -n "Deep" file.xml | cut -d: -f 1 | awk -F '[\t]' '{$NF = $NF -1;}1')

then run the sed line (or maybe also adjust that one):

sed $LineNum 's#^<Deep>#<!--<Deep>#g' > file.xml
  • sed "$LineNums#^#<!--#" file.xml -> this is not changing anything. The variable name is LineNum – DEEP MUKHERJEE Mar 10 '21 at 17:33
  • Note that you use an unset variable called LineNums in your sedcall. Also, it's unclear what you have changed in the code that that the user posted, apart from using $(...) in place of a backticked command substitution. When you correct the unset variable's name, this still has the same issue as the original code in that it will fail if there are multiple matches in the XML document. – Kusalananda Mar 10 '21 at 18:53