Is it possible to invoke a program such as Perl from a Bash script to perform a regex with named capture groups and export the results as variables back to the parent shell?
For example:
#!/bin/bash
input="a small box"
regex="a (?P<size>\w+) box"
perl -e "
my \$str = \"$input\";
if ( \$str =~ /$regex/ ) {
# Do a thing...
}
"
# Illustrative purposes only
echo $size
The expected output would be small
.
This doesn't have to be done with Perl specifically. I just want to know if this can be done and demonstrated.
I have a few thousand files to parse and need to build a very large and complex regular expression to handle their contents. While this can be done with other tools such as pcregrep
or =~
with numbered capture groups, I would prefer to use named capture groups for clarity.
I don't feel that I need to use anything other than Bash except for the heavy lifting of this complex regular expression. Is there a way to easily drop into another language to take advantage of named capture groups and export the result back to the parent environment?
There is no way to export a variable from a subprocess to a parent process.
The closest to that would be child process giving output in a way that a bash shell can evaluate. E.g. if your perl program would output
then you can invoke it from
bash
like this:and those variables would be inserted into your environment:
EDIT: With Ruby, assuming
input
andregex
are defined,