Last active
March 30, 2020 13:58
-
-
Save mohd-akram/aa726c66e88a380b6d0979beb9315e26 to your computer and use it in GitHub Desktop.
Escape POSIX (grep, sed, ex) regular expression patterns and replacements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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