#!/usr/bin/env bash
# -i rewrites the files named on the command line with whatever the program
# prints. With -p that is every line; with -n it is only the lines you print,
# and a print that goes somewhere else leaves the file empty.
#
# Runs in a scratch copy of ../demo, so the lesson folder stays clean.
set -u
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
cp ../demo/orders.txt "$work"/
cd "$work" || exit 1

say() { printf '$ %s\n' "$*"; eval "$*" 2>&1; echo; }

say "perl -i.bak -pe 's/Warsaw/Warszawa/' orders.txt"
say ls
say cat orders.txt
say cat orders.txt.bak
say "perl -MO=Deparse -i.bak -pe 's/Warsaw/Warszawa/' 2>/dev/null"

say "perl -i -ne 'print unless /bob/' orders.txt"
say ls
say cat orders.txt

say "mkdir originals && perl -i'originals/*' -pe 's/alice/Alice/' orders.txt"
say "ls originals"
say cat orders.txt

say "perl -i -ne 'print STDOUT \"read: \$_\"' orders.txt"
say "test -s orders.txt || echo 'orders.txt is now empty'"
