aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEuAndreh <eu@euandre.org>2023-03-03 13:56:08 -0300
committerEuAndreh <eu@euandre.org>2023-03-03 13:56:08 -0300
commit084fb72a12d73cb8a22beb7f85d1b6b05de7081a (patch)
tree8e7383e610245a9e87fcb0c0d85b156967069b1c
parentbin/vcs: Update help string (diff)
downloaddotfiles-084fb72a12d73cb8a22beb7f85d1b6b05de7081a.tar.gz
dotfiles-084fb72a12d73cb8a22beb7f85d1b6b05de7081a.tar.xz
bin/re: Add working utility
-rwxr-xr-xbin/re97
1 files changed, 97 insertions, 0 deletions
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