diff options
author | EuAndreh <eu@euandre.org> | 2023-03-03 13:56:08 -0300 |
---|---|---|
committer | EuAndreh <eu@euandre.org> | 2023-03-03 13:56:08 -0300 |
commit | 084fb72a12d73cb8a22beb7f85d1b6b05de7081a (patch) | |
tree | 8e7383e610245a9e87fcb0c0d85b156967069b1c /bin/re | |
parent | bin/vcs: Update help string (diff) | |
download | dotfiles-084fb72a12d73cb8a22beb7f85d1b6b05de7081a.tar.gz dotfiles-084fb72a12d73cb8a22beb7f85d1b6b05de7081a.tar.xz |
bin/re: Add working utility
Diffstat (limited to 'bin/re')
-rwxr-xr-x | bin/re | 97 |
1 files changed, 97 insertions, 0 deletions
@@ -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 |