使用 bash 从文本文件中删除 ANSI 颜色代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19296667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:15:56  来源:igfitidea点击:

Remove ANSI color codes from a text file using bash

bashshell

提问by Lurch

I have a bash script that runs and outputs to a text file however the colour codes it uses are also included what i'd like to know is how to remove them from the file, ie

我有一个运行并输出到文本文件的 bash 脚本,但是它使用的颜色代码也包括在内,我想知道如何从文件中删除它们,即

^[[38;1;32mHello^[[39m
^[[38;1;31mUser^[[39m

so I just want to be left with Hello and User

所以我只想留下你好和用户

回答by sandy_1111

sed -r "s/\x1B\[(([0-9]{1,2})?(;)?([0-9]{1,2})?)?[m,K,H,f,J]//g" file_name

this command removes the special characters and color codes from the file

此命令从文件中删除特殊字符和颜色代码

these are some of ANSI codes: ESC[#;#H or ESC[#;#fmoves cursor to line #, column # ESC[2Jclear screen and home cursor ESC[Kclear to end of line,

这些是一些 ANSI 代码: ESC[#;#H or ESC[#;#f将光标移动到第 # 行,第 # 列 ESC[2J清除屏幕和主页光标 ESC[K清除到行尾,

note in case of clear code there is neither number nor semicolon ;

请注意,如果代码清晰,则既没有数字也没有分号 ;

agree with below comment: if the numbers are more than 2 digit kindly use this:

同意以下评论:如果数字超过 2 位,请使用:

sed -r "s/\x1B\[(([0-9]+)(;[0-9]+)*)?[m,K,H,f,J]//g" filename

回答by Wiimm

My solution:

我的解决方案:

... | sed $'s/\e\[[0-9;:]*[a-zA-Z]//g'

The colon is there to support escapes for some old terminal types.

冒号用于支持某些旧终端类型的转义。

回答by MacUsers

Does this solve the issue?

这能解决问题吗?

$ echo "^[[38;1;32mHello^[[39m" | sed -e 's/\^\[\[[0-9;]\{2,\}m//g'
Hello

cheers!!

干杯!!