The Chalkboard


Remove terminal colour codes from a text file that was piped in to

Last Updated: [2023-03-29 Wed 07:07]

I have made this mistake in the past: Piped the output of a file into a document only to find I’ve accidentally pipped the terminal colour information into the file too (e.g. the output of jq -C . into a JSON file, which, of course, makes it unparsable. Thankfully, sed and regex can come to the rescue here:

Linux and WSL

FILE=textfile.txt ; cat "${FILE}" | sed -r "s/\x1B\[([0-9]{1,3}(;[0-9]{1,2};?)?)?[mGK]//g" | sponge "${FILE}"

macOS

You will need gsed and sponge from Homebrew

FILE=textfile.txt ; cat "${FILE}" | gsed -r "s/\x1B\[([0-9]{1,3}(;[0-9]{1,2};?)?)?[mGK]//g" | sponge "${FILE}"

Job’s a goodun!


DISCLAIMER: The information provided on this website is generated from my own notes and is provided "as is" and without warranties. Robert Ian Hawdon can not be held responsible for damages caused by following a guide published on this site. This website contains links to other third-party websites. Such links are provided as convienice of the reader. I do not endorce the contents of these third party sites.