I have a file with some non-printable characters that come up as ^C or ^B, I want to find and replace those characters, how do I go about doing that?
7 Answers
Removing control symbols only:
:%s/[[:cntrl:]]//g
Removing non-printable characters (note that in versions prior to ~8.1.1 this removes non-ASCII characters also):
:%s/[^[:print:]]//g
The difference between them could be seen if you have some non-printable-non-control characters, e.g. zero-width space:
12 Comments
Say you want to replace ^C with C:
:%s/CtrlVC/C/g
Where CtrlVC means type V then C while holding Ctrl pressed.
CtrlV lets you enter control characters.
1 Comment
Try this after saving your file in vim (assuming you are in Linux environment)
:%!tr -cd '[:print:]\n'
2 Comments
:% filters all lines using the external (!) programm tr, which removes (-d) all characters that are not (-c) printable ([:print:]) or newline (\n).tr will strip the Unicode data when using [:print:].None of the answers here using Vim's control characters worked for me. I had to enter a unicode range.
:%s/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]//g
That unicode range was found on this other post: https://stackoverflow.com/a/8171868/231914
1 Comment
An option not mentioned in other answers.
Delete a specific unicode character with a long hex code, e.g. <200b>:
:%s/\%U200b//g

/[^ -~]Found this answer here: stackoverflow.com/a/23103760/1663462