Given this file:

printf 'hello\x19world\n' > hello.txt

I can replace a hex character:

$ ex -sc '%s/\%x19/ /|x' hello.txt
$ od -c hello.txt
0000000   h   e   l   l   o       w   o   r   l   d  \n

However I cannot replace with a hex character:

$ ex -sc '%s/ /\%x19/|x' hello.txt
$ od -c hello.txt
0000000   h   e   l   l   o   %   x   1   9   w   o   r   l   d  \n

From :help todo:

Substitute with hex/unicode number "\%xff" and "\%uabcd". Just like "\%uabcd" in search pattern.

In other words, this isn't implemented yet.

You can do it interactively, in Vim. See :help 24.8.

Type :%s/ /, then type Ctrl-V, then x19, then press Enter.

  • Most shells allow a similar input mechanism
    – D. Ben Knoble
    Apr 10 '20 at 21:00

Yes you can do this easily. You just have to use an expression in the replacement part (see the help at :h sub-replace-expression link).

So you would do it like this:

ex -sc '%s/ /\="\x19"/g|x' hello.txt
 od -c hello.txt
 0000000   h   e   l   l   o 031   w   o   r   l   d  \n

See the help at :h expr-quote link

  • Sorry, but all that does it remove the space for me
    – Zombo
    Nov 17 '16 at 12:50
  • what vim version? Nov 17 '16 at 13:16
  • VIM - Vi IMproved 7.4
    – Zombo
    Nov 18 '16 at 2:23
  • please show the complete output Nov 18 '16 at 6:55

You can pass it from the shell:

ex -sc $'%s/\031/\027/|x' hello.txt

This will pass the literal ^Y and ^[ characters to ex, which seems to work fine. You can also enter a literal character as ^V^Y (control+v control+y) in most shells.


I figured it out a solution:

:s/\%x19/ /g

TIP: The value \x19 can be expressed on Unicode by \u0019. So you can do:

:s/ /\="\u0019"/g

When you press ga you can see the hex value, if it has less than four digits fill it with zeros and you have the Unicode value

For example Xex 20 (space), can be \u0020 and in the search pattern we have to use backslash + percent + (u|x|o) followed by its number.

On the substitution portion, you have to use an expression register if we want to use any (unicode|hex|octal) replacement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.