Reputation: 187
I have a bash script which I have made the output pretty with colors and stuff, however my log file looks horrible.
If it can be modified before it is piped to the log file that would be preferable but if that is not possible i would like to at least run a clean-up function that could be run at the end of my script which would clean the log file of the ugliness.
I have tried things like sed -r -i "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" install.log
but that did not seem to clean up
Below are the color variables used
BOLD=$(tput bold); RED=$(tput setaf 1); WHITE=$(tput setaf 7); BGBLUE=$(tput setab 4); BGRED=$(tput setab 1); RCol=$(tput sgr0); InCol=$(tput rev); UndLn=$(tput smul)
BWhiOn_Red=$BOLD$WHITE$BGRED; BWhiOn_Blu=$BOLD$WHITE$BGBLUE; BRed=$BOLD$RED;
Here is an code snippet
printf "%s\n" "${BRed}MISSION ABORTED! Abandon Ship!!${RCol}" | tee -a install.log
And this is what it looks like when I vi the log file
^[[1m^[[31mMISSION ABORTED! Abandon Ship!!^[(B^[[m
When using sed -r -i "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" install.log
the log file shows this
MISSION ABORTED! Abandon Ship!!^[(B
It seems like the regex doesn't cover tput sgr0
but i am not sure how to fix it
Upvotes: 1
Views: 689
Reputation: 69198
To avoid the problem
if [ -t 1 ]
then
BOLD=$(tput bold);
RED=$(tput setaf 1)
...
fi
and the values won't be set if you redirecting to a file
Upvotes: 1
Reputation: 6158
This worked for me:
sed -i -e 's/\x1B[^m]*m//g' install.log
To break down the sed command, the \x1B
is the escape character that starts a control sequence: Ctrl-[
. A control sequence ends with an m
, so we find every character that is NOT an m, and the m that follows: [^m]*m
.
Upvotes: 1