in reply to ho w to replace a occurence of string by other string

i am using a file say file1.txt . in that file i am refering to files like xxx1.data etc. in all the occurences i want to append this string as $testname/xxx1.data( preceed the xxx1.data with $testname. here $testname is a variable name which is having some value and has been set earlier and i m using its value by calling the scalar). now what i had tried actually replaces the xxx1.data , i do not want to delete the string only add new text before it. Thanks sachin

Replies are listed 'Best First'.
Re: how to modify the text in file
by Thilosophy (Curate) on Jan 19, 2005 at 07:07 UTC
    now what i had tried actually replaces the xxx1.data , i do not want to delete the string only add new text before it.

    What have you tried? Show us some code...

    If you tried

    s[\w\w\w1\.data][$testname/]g
    you might consider
    s[(\w\w\w1\.data)][$testname/$1]g
    instead.

    The $1 stands for the text enclosed in the first set of round brackets in the pattern.

      i was using something like perl -npi.bak -e "s:(\w\d+\.data):testname/$1:g" file1.txt . it actually repleces the text and do not do what i wanted
        1. First, you need to replace "\w\d+" with "\w+\d+". Otherwise, your regex is only going to match "x1.data" instead of "xxx1.data".
        2. Second, I assume you're using bash, sh, or a similar shell on a Unix box. When passing arguments using double-quotation marks, you need to escape any backslashes, dollar signs, and certain other characters. I recommend using single-quotation marks instead since most characters don't have to be escaped inside them.

        Suggestion:

        perl -npi.bak -e 's:(\w+\d+\.data):testname/$1:g' file1.txt
        
        Aha !
        perl -npi.bak -e "s:(\w\d+\.data):testname/$1:g" file1.txt
        That is a shell quoting problem. Your $1 gets replaced by an (empty) environment variable before Perl sees it. Use single quotes:
        perl -npi.bak -e 's:(\w\d+\.data):testname/$1:g' file1.txt