I need to replace all the occurrences of 
with 0x02
using sed
. Will the following work or I'll have to use \
?
sed -i -E "s/<>/<0x02>/g" $output_file
If yes, how can I do that?
I need to replace all the occurrences of 
with 0x02
using sed
. Will the following work or I'll have to use \
?
sed -i -E "s/<>/<0x02>/g" $output_file
If yes, how can I do that?
There are no special characters in the string 
that needs to be escaped for the string to be interpreted literally in the pattern part of a s///
command in sed
.
There are furthermore no special characters in the replacement string 0x02
that needs to be treated specially (&
would have been special in the replacement, as would \1
, \2
etc. and \n
, \t
etc. if you're using GNU sed
).
This means you should be able to just do
sed 's//0x02/g' inputfile >outputfile
The only thing that may need to be treated especially is to avoid replacing 
when it occurs in substrings such as #
. Since I don't see any example document in the question I can't say exactly if this would be an issue and how to best protect against it.
In general, don't use the -i
option with sed
until you have a sed
editing expression or script that you know works, to avoid accidentally loosing data. You also don't need -E
here as we're not dealing with extended regular expressions at all.
If you are running the sed
command on a file whose name is kept in a variable, remember to double quote the expansion of that variable (see Why does my shell script choke on whitespace or other special characters?).
-i
option tosed
works very differently on various systems. You also include<
and>
in your pattern and replacement text, could you explain why (these weren't in the question before then)? The pattern is a string, not a regular expression, so the-E
option seems not needed (it enables extended regular expressions, of which you use none). Also, are you wanting to run this on some file whose name is in the variableoutput_file
, or shoud that be the output file name, as opposed to the input file name (which isn't mentioned)? – Kusalananda Mar 18 '21 at 10:59