LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Find and replace a string in a file using perl command from bash script (https://www.linuxquestions.org/questions/programming-9/find-and-replace-a-string-in-a-file-using-perl-command-from-bash-script-862691/)

koundinya749 02-14-2011 06:51 PM

Find and replace a string in a file using perl command from bash script
 
Hi,
I wanted to find and replace a string from a perl file. I have written a script in bash which runs the following command.

perl -pi -e "s/$findstring/$replacestring/" testfile

where as $findstring = print F_WC_TMP"$line\n";
and $replaceString = $line = join ' ', split ' ', $line; print F_WC_TMP"$line\n";

But when I am running the above command, i think it is replacing the $findstring with the above mentioned string and hence it contains a $line, it is looking for the variable $line and not finding the exact string. I am confused about how to search for a string that contains $ in it and replace it with another $string. Please help me on this

risu 02-15-2011 02:12 AM

Try to precede the $'s and the \'s with a \ (i.e. escape them), in both findstring and replacestring:

#!/bin/bash
findstring='print F_WC_TMP"\$line\\n";'
replacestring='\$line = join " ", split " ", \$line; print F_WC_TMP"\$line\\n";'
perl -pi -e "s/$findstring/$replacestring/" testfile

Risto

hsmak_linux 02-15-2011 02:16 PM

If you understood you, you want a Perl script do you this. Here it is:

================================
PHP Code:

#!/usr/bin/perl
# command: ./thiscode.pl str1 str2 testfile

# @ARGV is the array where arguments from the command line are stored
$str1 $ARGV[0];
$str2 $ARGV[1];

open(FILE$ARGV[2]) or die "Can’t open $ARGV[1] : $!\n";

while(
$line = <FILE>){
    
chomp ($line);
    
    print 
"Before substituting: "$line ,"\n";
    
$line =~ s/$str1/$str2/g;    
    print 
"After substituting : "$line ,"\n\n";


==================================

That should do it..
Good luck!

koundinya749 02-15-2011 03:53 PM

Hello,
Thanks a lot. It worked. :)

I have one more question. Actually I wanted to insert a new line before an already existing line. Thats why I am searching for the existing line and replacing it with a newline;existing line. But Is there any way just to insert a new line before an existing line without replacing it?

Thanks.

risu 02-15-2011 04:02 PM

What if you insert a newline character into replacestring instead of space (after the first semicolon):

replacestring='\$line = join " ", split " ", \$line;\nprint F_WC_TMP"\$line\\n";'

Risto

koundinya749 02-15-2011 04:52 PM

Yes. It worked. Thanks a lot.


All times are GMT -5. The time now is 05:59 PM.