Remove color codes from output with sed in Linux bash
In Linux bash, it’s common to use command line tools to get information and output results. Sometimes, the output includes color codes that can be distracting or make it difficult to read. In this blog post, we will discuss how to remove color codes from output using sed, a powerful text editor that is built into Linux.
sed script slice could help you remove color codes from the output of linux bash terminal.
cat output | sed "s,\x1B\[[0-9;]*[a-zA-Z],,g"
Using sed to remove color codes
Sed is a command-line utility that can be used to edit text files directly or to filter text in a pipeline. One of its most powerful features is the ability to search for and replace specific patterns of text. We can use this feature to remove color codes from output.
To remove color codes from the output of a command, first, run the command and then pipe the output to sed. Here’s an example that shows how to remove color codes from the output of the ls command:
ls --color | sed 's/\\x1b\\[[0-9;]*m//g'
In this command, the
ls command is run with the
--color option to add color to the output. The output is then piped to sed, which searches for the color codes and removes them. The
s command is used to search and replace, and the regular expression
\\x1b\\[[0-9;]*m matches the color codes. The
g flag is used to replace all occurrences of the pattern.
Creating an alias
Typing out the sed command every time you want to remove color codes from output can be tedious. Fortunately, you can create an alias to make this process easier. An alias is a short name or abbreviation that you can use to represent a longer command.
To create an alias for the sed command we used earlier, open your shell configuration file (
.zshrc) and add the following line:
alias nocolor="sed 's/\\x1b\\[[0-9;]*m//g'"
Save the file and then reload your shell configuration by running the command:
Now you can use the
nocolor alias to remove color codes from the output of any command. For example, you can run
ls --color | nocolor to get a color-free output of the
Removing color codes from output can make it easier to read and manipulate the information generated by command line tools in Linux. Sed is a powerful tool that can help you achieve this goal quickly and easily. By using sed to filter out color codes, you can focus on the content of the output and be more productive in your work. With the alias we created, you can make this process even more efficient.
- Welcome to visit the knowledge base of SRE and DevOps!
- License under CC BY-NC 4.0
- Made with Material for MkDocs and improve writing by generative AI tools
- Copyright issue feedback me#imzye.com, replace # with @