如何移除文件中仅在vi编辑器可见的^[[0m控制字符?
^[[0m) in Your File Hey there! Let's sort out that pesky ^[[0m control character showing up in vi—those are ANSI escape codes used for text formatting, which cat automatically handles (so they don't show up) but vi displays as raw characters. Here are a few simple, reliable ways to remove them:
Use
sedto clean the file in one go
This command will globally remove all ANSI formatting escape codes from your file (not just^[[0m, but any similar ones like bold/color codes):sed -i 's/\x1b\[[0-9;]*m//g' test.txtBreakdown:
\x1brepresents the ESC character (the start of all ANSI escape codes),\[[0-9;]*mmatches the rest of the format sequence, and//greplaces every occurrence with nothing.Clean it directly in
vi
If you prefer doing it right in the editor, opentest.txtwithvithen run this substitution command::%s/\x1b\[[0-9;]*m//gHit Enter, then save with
:w—your file will be free of those control characters immediately.Alternative: Use
trfor quick removal (limited to ESC-based codes)
If you only need to strip the ESC character and its following sequence, you can usetrto delete all ESC characters:tr -d '\033' < test.txt > temp.txt && mv temp.txt test.txtNote: This is less thorough than
sedsince it only removes the ESC character, but it works if your only issue is the^[[0msequence.
After running any of these, open the file with vi again—those annoying ^[[0m strings should be gone, and cat will still display the content as expected!
内容的提问来源于stack exchange,提问作者Sanjay Shitole

