passing variable from bash to perl in a bash script
Hello,
I need to find the first position of an exact substring (not a regular expression) inside a substring and bash is not adequate. For example in the following bash snippet, 1 will be echoed because the first position of either "a" or "t" in "adequate" is 1 : #!/bin/bash MYVARIABLE="adequate" POSITION=`expr index "$MYVARIABLE" at` echo $POSITION exit I could embed the following Perl in my bash script: #!/bin/bash echo "Index value is..." # Embedded Perl script. POSITION=`perl -e 'print index("Once upon a time","im");'` echo $POSITION exit Now the problem: How do I replace "Once upon a time" and "im" in the embedded Perl line with bash variables? I need to do: #!/bin/bash MYVARIABLE="adequate" MYSUBSTRING="at" # Embedded Perl script. POSITION=`perl -e 'print index($MYVARIABLE,$MYSUBSTRING);'` echo $POSITION exit |
Missing quotes, no?
Try: POSITION=`perl -e 'print index("$MYVARIABLE","$MYSUBSTRING");'` |
Nope
Nope, the following will echo "0"
#!/bin/bash MYVARIABLE="adequate" MYSUBSTRING="at" # Embedded Perl script. POSITION=`perl -e 'print index("$MYVARIABLE","$MYSUBSTRING");'` echo $POSITION exit |
single-quote works
The following works, echoing "5":
#!/bin/bash MYVARIABLE="adequate" MYSUBSTRING="at" # Embedded Perl script. POSITION=`perl -e 'print index('$MYVARIABLE','$MYSUBSTRING');'` echo $POSITION exit |
Hi.
Double quotes will work: Code:
#!/bin/bash Code:
% ./s1 Code:
POSITION=$(perl -e "print index($MYVARIABLE,$MYSUBSTRING);") ( edit 1: add, clarify ) |
why not do the whole problem in perl?
|
Inspired by awk code.
For awk who want to use bash variable:
awk -F" " {'if ($2=="'${BASH_VAR}'") print $7'} For Perl who want to use bash variable: Quote:
Actually, it's bash's job to expand ${BASH_VAR} rather than perl. These code explain a lot. BTW: I do love 'perl -ne' |
All times are GMT -5. The time now is 07:03 PM. |