Hex codes in sed - not working as expected on OSX

The answer to my question may exist on SO, but I honestly looked hard and can't find it. The closest I got this Q & A , but I could not reproduce their results on my machine (OSX 10.7.5 using bash).

Here is a problem that boils down to its essence: I cannot make sedinterpret \xnn(for example, \x41for A) as hexadecimal characters. What makes me, in particular, nuts:

echo -e '\x41' 

leads to A- so the OS and its functions understand my hex code ...

echo -e '\x41' | sed 's/A/B/'

leads to B- as expected since the hex code was converted to Abefore I sedsaw it

But

echo A | sed 's/\x41/B/'

leads to A- I would expectB

I tried things like

echo A | LANG='C' sed 's/\x41/B/'

leads to A

echo A | LANG='' sed 's/\x41/B/'

same...

echo A | sed 's/[\x41]/B/'

leads to A

BUT...

echo A | sed 's/[\x41-\x41]/B/'

leads to B

Am I absolutely stupid? Or is there really something strange with sed? Apparently, it can interpret hexadecimal code in a range, but I can't get it to be interpreted as a single character. What am I missing?

Please note: I’m looking for answers that explain why the above behaves the way it is done, and how to insert one hex code into any line sedon the OSX platform. This means both in the “search” and in the “replacement” of a part of the team s/. Since I obviously showed that I can find one character with [\ xnn- \ xnn]; this is not the answer i am looking for.

Thanks in advance!

+5
source share
2

, " " - , .. , .. , sed . bash ( ), sed $'':

$ echo A | sed $'s/\x41/B/'
B

, escape-, sed, , sed, , $'':

$ echo A | sed $'s/\\(\x41\\)/B\\1/' # double-escapes for sed escape sequences
BA
$ echo A | sed 's/\('$'\x41''\)/B\1/' # equivalent with different quote modes
BA
$ echo A | sed 's/\(A\)/B\1/' # simplest equivalent version
BA

escape- , , printf builtin:

$ hex=41
$ echo A | sed "s/$(printf "\x$hex")/B/"
B
+8

@GordonDavisson ...

-, ,

echo A | sed 's/[\x41-\x41]/B/'

, , sed \xnn , .

echo A | sed 's/[\x40-\x40]/B/'

I B, , A (\x41) . , sed - , . man re_format. :

[...] , `\ ', .

: echo -e , , , , sed...

echo "This?" | sed `echo -e 's/\x54\x68\x69\x73\x3F/\x59\x65\x73\x21/'`

Yes!

echo "That?" | sed `echo -e 's/\x54\x68\x69\x73\x3F/\x59\x65\x73\x21/'`

That?

, \xnn ASCII-, 's/This?/Yes!/', sed. , , - " , , sed. - -" sed. , ... sed ( , "" , -E "" re_format re_syntax, re_format. , ...

"", "" , , ... !

+3

All Articles