Had a colleague ask me how to do in-line regular expression matching for a Bash shell script. Since Bash v3 only offers a regex matching check and not the full s/foo/bar/ syntax, I offered to look into other alternatives.
My natural instinct was to look for a Perl cmdline regex parser, which works great if you're manipulating a file and not shell variables.
In the end, since he only needed a simple search and replace, and not an actual regular express, this suffices:
#!/bin/bash '{ sub(srch,repl,$0); print $0 }'`
VAR1="foobar"
VAR2=`echo $VAR1 | awk -v srch="foo" -v repl="bar" \
echo $VAR1
echo $VAR2
your awk could be replaced with perl -p:
VAR2= ` echo $VAR1 | perl -pe 's/foo/bar/g' `I prefer the readability of $( ) over “ for shell escaping. (Plus, I use back-tick as my screen key, as you know)
VAR2=$( echo $VAR1 | perl -pe 's/foo/bar/g' )Or hey, you could be using zsh for the shell script:
#!/usr/bin/zwsh
VAR1="FOO"
VAR2=${VAR1:s/FOO/BAR}echo "1:$VAR1, 2:$VAR2"–andrew
ps. Thanks for making me look up the zsh syntax for this particular "parameter expansion"
your awk could be replaced with perl -p:
VAR2= ` echo $VAR1 | perl -pe 's/foo/bar/g' `I prefer the readability of $( ) over “ for shell escaping. (Plus, I use back-tick as my screen key, as you know)
VAR2=$( echo $VAR1 | perl -pe 's/foo/bar/g' )Or hey, you could be using zsh for the shell script:
#!/usr/bin/zshVAR1="FOO"VAR2=${VAR1:s/FOO/BAR}echo "1:$VAR1, 2:$VAR2"–andrew
ps. Thanks for making me look up the zsh syntax for this particular "parameter expansion"