Removing ANSI escape codes in Vim

Featured image for sharing metadata for article

Sometimes you'll be working with tools that may end up (accidentally) writing ANSI escape codes to the console, and these can be captured by tools like tee and then end up in a file.

^[[00;32mSuccessful deployment^[[0m
\033[00;32mhuzzah, the thing has been done!\033[0m

I generally hand write this as the below:

:%s/^[[[0-9]*;[0-9]*m//g
# NOTE that the ^[ here is the _literal_ escape character so you need to actually do
# <C-V><Esc> instead of ^[
:%s/^[[[0-9]*m//g

However, as noted above, this is a bit awkward as it requires the escaping of the escape character so can't be saved in a command easily, or copy, pasted.

We can instead take inspiration from this StackOverflow and craft the following, which uses the character set that this belongs to:

# for the first pattern, with a literal escape
:%s/[\x1B]\[[0-9;]*m//g
# for the second pattern, without an escape
:%s/\\033\[[0-9;]*m//g

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #vim #neovim.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.