From 084fb72a12d73cb8a22beb7f85d1b6b05de7081a Mon Sep 17 00:00:00 2001 From: EuAndreh Date: Fri, 3 Mar 2023 13:56:08 -0300 Subject: bin/re: Add working utility --- bin/re | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100755 bin/re (limited to 'bin') diff --git a/bin/re b/bin/re new file mode 100755 index 0000000..c600aee --- /dev/null +++ b/bin/re @@ -0,0 +1,97 @@ +#!/bin/sh +set -eu + + +usage() { + cat <<-'EOF' + Usage: + re 'REGEXP' [FILE...] + re -h + EOF +} + +help() { + cat <<-'EOF' + + + Options: + -h, --help show this message + + REGEXP the regular expresion to match and replace + + + Execute a find and replace on files in a repository when + no FILE... is given, listing them via "vcs ls" from vcs(1), or + on the given FILE... list. + + EXPRESSION is to be forwarded to sed(1) directly. + + + Examples: + + Replace "weak" with "week" on the whole repository: + + $ re 's/weak/week/g' + + + Delete lines beginning with "import" on package.py: + + $ re '/^import/d' package.py + EOF +} + + +for flag in "$@"; do + case "$flag" in + --) + break + ;; + --help) + usage + help + exit + ;; + *) + ;; + esac +done + +while getopts 'h' flag; do + case "$flag" in + h) + usage + help + exit + ;; + *) + usage >&2 + exit 2 + ;; + esac +done +shift $((OPTIND - 1)) + +REGEXP="${1:-}" +eval "$(assert-arg -- "$REGEXP" 'REGEXP')" +shift + + +replace() { + FILE="$1" + if ! sed "$REGEXP" < "$FILE" | cmp -s - "$FILE"; then + if [ ! -e "$FILE" ]; then + return 1 + fi + sed "$REGEXP" < "$FILE" | sponge "$FILE" + fi +} + +if [ -n "${1:-}" ]; then + for f in "$@"; do + replace "$f" + done +else + vcs ls | while read -r f; do + replace "$f" + done +fi -- cgit v1.2.3