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 Answers 2
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
-
This printf '%s\n' 'g/Deep/-1 s/^/<!--/' 'w newfile.xml' 'q' | ed -s file.xml works perfectly if i want to insert the <!-- string at the start of the line above whatever lines contain Deep. However i also need to add --> at the 36 the line after the pattern matching at the end of the tag so the output looks like </ReconSummary>-->. 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– DEEP MUKHERJEE2021年03月11日 02:49:38 +00:00Commented Mar 11, 2021 at 2:49
-
@DEEPMUKHERJEE You question only concerned adding
<!--
. Conisder updating your question if you have other requirements.2021年03月12日 20:23:31 +00:00Commented Mar 12, 2021 at 20:23
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#^<Deep>#<!--<Deep>#" file.xml -> this is not changing anything. The variable name is LineNumDEEP MUKHERJEE– DEEP MUKHERJEE2021年03月10日 17:33:31 +00:00Commented Mar 10, 2021 at 17:33
-
Note that you use an unset variable called
LineNums
in yoursed
call. 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.2021年03月10日 18:53:11 +00:00Commented Mar 10, 2021 at 18:53
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
?