Skip to content

Instantly share code, notes, and snippets.

@sebastiancarlos
Last active January 23, 2024 10:49
Show Gist options
  • Save sebastiancarlos/c65befe823f3c15d20d2d9fce9d409a3 to your computer and use it in GitHub Desktop.
Save sebastiancarlos/c65befe823f3c15d20d2d9fce9d409a3 to your computer and use it in GitHub Desktop.
term2plain - Record an interactive terminal session, and convert it to plain text.
#! /usr/bin/env bash
# All my gist code is licensed under the MIT license.
# term2plain
# - Convert a text file containing terminal escape sequences to plain text.
# - This plain text is close to the visual result of running the file in a
# terminal.
# - This is achieved by running the file in a virtual terminal (tmux) and
# capturing it's buffer output.
# - For simple escape sequences like color, this might be overkill, but it's
# useful for interactive programs which read user input, and the cursor
# move sequences must be interpreted to produce the final input.
# - Example:
# $ interactive-program | tee output.txt # works for simple ones like
# # sqlite or gdb, not vim
# $ term2plain output.txt
# $ vim output.txt # see the plain-text output after escape sequences were
# # processed by a virtual terminal.
# Store the file path and the name for the tmux session
file_path="$1"
session_name="term2plain_session"
output="/tmp/term2plain_output.txt"
start_marker="#term2plain-start"
end_marker="#term2plain-end"
SLEEP_TIME=0.1 # adjust sleep as needed based on file size
# bail if tmux is not installed
if ! command -v tmux &> /dev/null; then
echo "Error: tmux is not installed"
exit 1
fi
# Create a new detached tmux session
tmux new-session -d -s "$session_name"
# Send the 'cat' command to the session
tmux send-keys -t "$session_name" "cat '$file_path'" ' \' C-m "$start_marker" C-m
# Wait a little to make sure 'cat' has finished
sleep $SLEEP_TIME
# type end marker
tmux send-keys -t "$session_name" "$end_marker" C-m
# Capture the pane output
tmux capture-pane -pS - -t "$session_name" >| "$output"
# Kill the tmux session
tmux kill-session -t "$session_name"
# remove everything before and after markers
sed -i -e '1,/'"${start_marker}"'/d' "$output"
sed -i -e '/'"${end_marker}"'/,$d' "$output"
# Print the captured output
cat "$output"
/usr/bin/rm "$output"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment