0

I need to replace all the occurrences of &#x2 with 0x02 using sed. Will the following work or I'll have to use \?

sed -i -E "s/<&#x2>/<0x02>/g" $output_file

If yes, how can I do that?

Kusalananda
  • 333,661
  • 2
    What Unix are you on? The -i option to sed 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 variable output_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
  • Basically I need to replace all the occurrences of with 0x02. I am unable to figure out if the pattern is a string simply or is considered as special characters since it starting with &? output_file is a variable name – user13583928 Mar 18 '21 at 11:09

1 Answers1

1

There are no special characters in the string &#x2 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/&#x2/0x02/g' inputfile >outputfile

The only thing that may need to be treated especially is to avoid replacing &#x2 when it occurs in substrings such as &#x23. 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?).

Kusalananda
  • 333,661