LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Embedding perl in bash script (https://www.linuxquestions.org/questions/programming-9/embedding-perl-in-bash-script-284824/)

MikHud 02-01-2005 05:28 AM

Embedding perl in bash script
 
I want to put the following perl 'find and replace' command into a script:-

perl -i.backup -p -e 's/old string/new string/g' *.pattern

- so that I only have to use the name of the script followed by old string and new string.

If I try to embed the above perl command in a bash script I can't figure out how to pass the string parameters to perl. Replacing the strings in the command with $1 and $2 or "$1" and "$2" doesn't work. Can perl access the args to the bash script or would it be best to just put turn this command into a perl script and pass the strings directly to it?

But then as a perl virgin I don't know how to put the perl command into a script and then pass the strings to it.

Any help appreciated.

Disillusionist 02-01-2005 12:25 PM

Shell script for you:

Code:

# Program change_file
# Syntax: change_file search_string replace_string file
v_search=$1
v_replace=$2
v_file=$3

perl -i.backup -e"s/${v_search}/${v_replace}/g" -p ${v_file}

# Optional Exctra
rm ${v_file}.backup

If you want to search for more than one word enclose the string in single quotes

EG:

change_file 'more than words' 'can say' target

scissors 02-01-2005 12:42 PM

I would just make it all shell or all perl to minimize confusion, I would suggest all perl, to give yourself some more practice with it. What is it that you are trying to do? The perl line does not make sense to me. If you are simply trying to make a backup of files by passing the old and new string through, maybe this is what you want:

perl -i.$2 -p *.$1

If you write this all in perl, instead of $1 and $2 we use $ARGV[0] and $ARGV[1].

Disillusionist 02-01-2005 01:03 PM

The perl line is creating a backup of the file (extension .backup) and doing a global search and replace on the given strings the output is then stored in the original file.

To do this in shell only:

Code:

# Shell only

cp -p $3 $3.backup
sed 's/$1/$2/g' $3.backup > $3

I've not played with perl enough to translate into a pure perl script.

MikHud 02-02-2005 06:26 AM

Many thanks for your help Disillusionist.

I forgot about the difference between single and double quotes!

Regards
MikHud


All times are GMT -5. The time now is 12:42 AM.