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?

share|improve this question
up vote 20 down vote accepted

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.

share|improve this answer
1  
You can also use Ctrl-Q. This is useful for some users who map Ctrl-V to clipboard operations – Iain Ballard Feb 19 '15 at 15:52

Removing control symbols only:

:%s/[[:cntrl:]]//g

Removing non-printable characters (removes non-ASCII characters also):

:%s/[^[:print:]]//g
share|improve this answer
    
At least until vim 7.3 [:print:] only matches ASCII printable characters (edited the answer to alert readers about this fact) – ndemou Feb 10 '15 at 22:00
    
@ndemou This is tricky, with the [ ] around the [:print:] the ^ should invert the match and return any non-printable. Or perhaps that was your edit? – dragon788 Mar 2 '16 at 0:43
    
@dragon788, yes I was aware of how it works when I wrote my comment. Try the 2nd regex on text with printable Unicode characters outside the ASCII table to understand my comment (it will remove the Unicode characters). – ndemou Mar 2 '16 at 12:16

Try this after saving your file in vim (assuming you are in Linux environment)

:%!tr -cd '[:print:]\n'
share|improve this answer
5  
please explain this day saving magic voodoo! – Prospero Nov 26 '12 at 20:13
3  
@JamesAndino: :% filters all lines using the external (!) programm tr, which removes (-d) all characters that are not (-c) printable ([:print:]) or newline (\n). – quasimodo Feb 7 '14 at 18:08
2  
This isn't Unicode friendly, as it is a POSIX character class (en.wikipedia.org/wiki/Regular_expression#Character_classes)‌​. So if you have YAML with data like 你好, tr will strip the Unicode data when using [:print:]. – ash Feb 10 '14 at 1:40

You can use the CTRL-V prefix to enter them, or if they're not easily typeable, yank and insert them using CTRL-R ".

share|improve this answer

You can use:

:%s/^C//g

To get the ^C hold the control key, press V then C (Both while holding the control key) and the ^C will appear. This will find all occurrences and replace them with nothing.

To remove both ^C and ^B you can do:

:%s/^C\|^B//g
share|improve this answer

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: http://stackoverflow.com/a/8171868/231914

share|improve this answer
    
Because TAB is considered not-printable, So these [[:cntrl:]] and [^[:print:]] match TAB (0x9, C-I) – mosh Jan 15 at 3:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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