I need to process a file line-by-line using some value from a shell variable
Something like:
perl -p -e 's/$shell_srch/$shell_replace/g' input.txt
I can't make the '-s' work in the '-p' or '-n' input loop (or couldn't find a syntaxis.)
I have searched and found http://www.unix.com/302343759-post2.html, but it doesn't work
Is it possible (without havy sysntaxis, as ENV(..), for exmpl.) in the input loop?
Use doble quotes.
perl -p -e "s/$shell_srch/$shell_replace/g" input.txt
Sorry, it seems I did not explain enough.
My question is how to pass those 2 variables $shell_srch and $shell_replace into processing command.
So, I would have:
search_txt="programmer";
replase_txt="system engineer"
# something like that, but it doesn't work:
perl -p -e "s/$shell_srch/$shell_replace/g" input.txt shell_srch=$search_txt shell_replace=$replase_txt
In such way the perl trying to open files 'shell_srch=..' and 'shell_replace='
I thought it could be done with '-s' option to provide switches from command line, but I can't get it work.
Mayby you know proper sysntax to use '-s' together with -p or -n?
Maybe there is another way to pass shell-vars to the perl command?
P.S. Just realized dennis.jacob your advise: so, this way, with double-quotes, the shell will replace the variables by its values before start the perl.
But, how to make perl be able to work with own variables?
For example, I could need to use the '$_' and '$.' together.
Is this what you are looking for ?
$
$ cat f0
Andy is a programmer.
Bruce is a programmer.
Claire is a programmer.
$
$ SEARCH="programmer"
$ REPLACE="system engineer"
$
$ perl -ple "s/$SEARCH/$REPLACE/g" f0
Andy is a system engineer.
Bruce is a system engineer.
Claire is a system engineer.
$
$
tyler_durden
Yes, it is exactly what my example tying to do.
But I am looking for more general way to pass vars.
This way I should escape all special characters that shell would interpret to be passed to perl.
For example:
v1=25;
v2=30;
perl -ne "chomp; print \"\\nLine is:\$_\; \\\$v1=$v1\; \\\$v2=$v2\"; \
print \"\\n summ=\".($v1+$v2); " infl.txt
(I think the '-l' is not necessary or it is?)
This way it works, but it is uglee and hard to prepare and debug!
---------- Post updated at 01:11 PM ---------- Previous update was at 12:49 PM ----------
Just found some simplifying with the double-qoutes: it is possible to comby the perl command by multiple quoted strings:
> v1=25;
> v2=30;
> perl -ne 'BEGIN{$v1='"$v1"'; $v2='"$v2"';} chomp; print "$_ | summ=".($v1+$v2)."\n"' input.txt
line one | summ=55
line two | summ=55
third line | summ=55
one more line | summ=55
>
This is usefull already, but it is still way around!
It should be a way to do it simpler!
Anybody know?
Now, after 14 years, I know:
perl -s -- -perlvar="$shellvar"
perl -spe 's/$search/$replace/g' -- -search="$shell_srch" -replace="$shell_replace" input.txt
1 Like