Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

shell - Remove ANSI color codes from a text file using bash

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

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

so I just want to be left with Hello and User

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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[#;#f moves cursor to line #, column # ESC[2J clear screen and home cursor ESC[K clear to end of line,

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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...