Skip to content

Instantly share code, notes, and snippets.

@izabera
Last active March 23, 2023 12:32
Show Gist options
  • Save izabera/223f58d20be61911e62b to your computer and use it in GitHub Desktop.
Save izabera/223f58d20be61911e62b to your computer and use it in GitHub Desktop.
convert between asciinema and scriptreplay
#!/bin/bash
exec {times}> times {typescript}> typescript < "${1-/dev/stdin}"
while read -r; do [[ $REPLY = ' "stdout": [' ]] && break; done # skip to this line
LANG=C
printf "Script started on %(%c)T\n" -1 >&"$typescript" # dummy
while read -r open; [[ $open = '[' ]]; do
read -r elapsed; read -r string; read -r close
eval printf %b%n "$string" characters >&"$typescript" # put count in $characters
printf "%s %s\n" "${elapsed%,}" "$characters" >&"$times"
done
#!/bin/bash
backslash='\'
declare -A escapes=(
[$'\x01']='\u0001' [$'\x02']='\u0002' [$'\x03']='\u0003' [$'\x04']='\u0004'
[$'\x05']='\u0005' [$'\x06']='\u0006' [$'\x07']='\u0007' [$'\x08']='\b'
[$'\x09']='\t' [$'\x0a']='\n' [$'\x0b']='\v' [$'\x0c']='\f'
[$'\x0d']='\r' [$'\x10']='\u0010' [$'\x11']='\u0011' [$'\x12']='\u0012'
[$'\x13']='\u0013' [$'\x14']='\u0014' [$'\x15']='\u0015' [$'\x16']='\u0016'
[$'\x17']='\u0017' [$'\x18']='\u0018' [$'\x19']='\u0019' [$'\x1a']='\u001a'
[$'\x1b']='\u001b' [$'\x1c']='\u001c' [$'\x1d']='\u001d' [$'\x1e']='\u001e'
[$'\x1f']='\u001f' ['"']='\"'
)
times=() chars=() i=
while read -r "times[i]" "chars[i]"; do ((i++)); done < "${1-times}"
exec < "${2-typescript}" > "${3-asciinema}"
cat << cat
{
"version": 1,
"width": ${COLUMNS-$(tput cols)},
"height": ${LINES-$(tput lines)},
"duration": $(IFS=+; bc -l <<< "${times[*]}0"),
"command": "$SHELL",
"title": "",
"env": {
"TERM": "$TERM",
"SHELL": "$SHELL"
},
"stdout": [
cat
read -r start_time
IFS=
for (( j = 0; j < i; j++ )); do
LANG=C read "-rN${chars[j]}" string
string=${string//"$backslash"/$backslash$backslash}
for escape in "${!escapes[@]}"; do
string=${string//"$escape"/${escapes[$escape]}}
done
printf ' [\n'
printf ' %s,\n' "${times[j]}"
printf ' "%s"\n' "$string"
(( j < i-1 )) && printf ' ],\n' || printf ' ]\n'
done
printf ' ]\n}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment