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. Eg if your perl program would output
export LEGS=3
export ANIMAL='Lame boar'
then you can invoke it from bash
like this:
eval $(perl animal.pl)
and those variables would be inserted into your environment:
echo "$ANIMAL has $LEGS legs."
EDIT: With Ruby, assuming input
and regex
are defined,
eval $(ruby -r shellwords -e "
if (match = ENV['input'].match(ENV['regex']))
match.names.each do |name|
puts %{export #{name}=#{Shellwords::shellescape(match[name])}}
end
end
")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.