Last active
October 1, 2022 00:58
-
-
Save stephancasas/ee4323a98a65949fd81336a03b9bc99f to your computer and use it in GitHub Desktop.
losecontrol.sh — remove control characters from the logged output of a screen session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# ---------------------------------------------------------------------------- # | |
# losecontrol.sh | |
# ---------------------------------------------------------------------------- # | |
# | |
# Author: | |
# Stephan Casas <[email protected]> | |
# | |
# Description: | |
# Remove control characters from logged terminal output while maintaining the | |
# the on-screen output as plaintext. | |
# | |
# Why? | |
# Logged terminal output may include redundant data. Simply removing control | |
# characters will not yield reliable content. It is necessary to both remove | |
# the control characters while also evaluating those which modify the output | |
# text's visible (on-screen) plaintext value. | |
# ---------------------------------------------------------------------------- # | |
ESC=$(printf "\e") | |
BUF="" | |
while read -r LINE; do # read file by line | |
LINEBUF="" | |
ESCAPING=false | |
while read -r -n1 CHAR; do # read line by character | |
# unencode ifs entities | |
CODE=$(printf %d \'$CHAR) | |
# `NUL` -> Whitespace | |
[ $CODE -eq 0 ] && CHAR=" " | |
# `CR` -> Skip until output buffer | |
[ $CODE -eq 13 ] && CHAR="" | |
# buffer control sequence | |
$ESCAPING && CONTROL="$CONTROL$CHAR" | |
[ "$CHAR" = "$ESC" ] && ESCAPING=true && CONTROL="" | |
# buffer printable chars to line | |
! $ESCAPING && LINEBUF="$LINEBUF$CHAR" | |
# end control sequence at terminal char | |
$ESCAPING && | |
# `A-Z` -> [065:090] | |
eval "[ $CODE -gt 64 ] && [ $CODE -lt 91 ]" || | |
# `a-z` -> [097:122] | |
eval "[ $CODE -gt 96 ] && [ $CODE -lt 123 ]" || | |
# `=` -> [061:061] | |
eval "[ $CODE -eq 61 ]" && ESCAPING=false && | |
# simulate cursor reset | |
[ "$CONTROL" = "[0m" ] && STASH="$LINEBUF" && LINEBUF="" | |
done <<EOF | |
$LINE | |
EOF | |
# restore stash content if line empty | |
[ ${#LINEBUF} -eq 1 ] && APPEND="$STASH" || APPEND="$LINEBUF" | |
# buffer line to output and clear stash | |
BUF="$BUF$APPEND$(printf '\n\r')" && STASH="" | |
done <<EOF | |
$(cat $1) | |
EOF | |
echo "$BUF" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment