How do I replace or find non-printable characters in vim regex?

前端 未结 6 1680
青春惊慌失措
青春惊慌失措 2021-01-30 07:09

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?

相关标签:
6条回答
  • 2021-01-30 07:13

    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

    0 讨论(0)
  • 2021-01-30 07:27

    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.

    0 讨论(0)
  • 2021-01-30 07:31

    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:

    0 讨论(0)
  • 2021-01-30 07:31

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

    0 讨论(0)
  • 2021-01-30 07:35

    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
    
    0 讨论(0)
  • 2021-01-30 07:38

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

    :%!tr -cd '[:print:]\n'
    
    0 讨论(0)
提交回复
热议问题