Skip to content

Instantly share code, notes, and snippets.

@mohd-akram
Last active March 30, 2020 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohd-akram/aa726c66e88a380b6d0979beb9315e26 to your computer and use it in GitHub Desktop.
Save mohd-akram/aa726c66e88a380b6d0979beb9315e26 to your computer and use it in GitHub Desktop.
Escape POSIX (grep, sed, ex) regular expression patterns and replacements
#!/bin/sh
# Functions to escape strings for use in utilities like grep, sed and ex
# Examples
# grep "$(bre "$foo")" file
# sed "s/$(ptrn "$foo")/$(repl "$bar")/g" file
# echo "s/$(exptrn "$foo")/$(exrepl "$bar")/g | %p | q" | ex file
bre() {
# Escape string for use in POSIX BRE
# Chars: [ \ . * $ ^
printf '%s\n' "$1" | sed 's/[[\.*]/\\&/g; s/$$/\\&/; s/^^/\\&/'
}
ptrn() {
# Escape string for use in slash-delimited BRE pattern
# Chars: [ \ . * / $ ^
printf '%s\n' "$1" | sed 's/[[\.*/]/\\&/g; s/$$/\\&/; s/^^/\\&/'
}
repl() {
# Escape string for use in slash-delimited replacement
# Chars: \ & /
printf '%s\n' "$1" | sed 's/[\&/]/\\&/g'
}
exptrn() {
# Escape string for use in ex pattern
# Chars: [ \ . * / ~ $ ^
printf '%s\n' "$1" | sed 's/[[\.*/~]/\\&/g; s/$$/\\&/; s/^^/\\&/'
}
exrepl() {
# Escape string for use in ex replacement
# Chars: \ & / ~
printf '%s\n' "$1" | sed 's/[\&/~]/\\&/g'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment