Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

hi , i am having a text file , say output.txt. in that i am having variour occurences of strings with same extn like file1.data , file2.data etc. i want to replace all occurences of files names with .data extn with $testname/file1.data , $testname/file2.data etc . Please any one can help me out thanks sachin
  • Comment on ho w to replace a occurence of string by other string

Replies are listed 'Best First'.
Re: ho w to replace a occurence of string by other string
by borisz (Canon) on Jan 18, 2005 at 13:22 UTC
    untested:
    perl -pe 's:(\w+\.data)\b:testname/$1:g' <input >output
    Boris
Re: how to replace ocurence of string with other string
by Zaxo (Archbishop) on Jan 18, 2005 at 13:46 UTC

    perl -pi.bak -e'BEGIN{$testname="whatever"} s!([^/]+\.data)\b!$testname/$1!g' output.txt That will make the substitutions into output.txt which is backed up in a file called output.txt.bak.

    [Update: edited for thinko, VSarkiss++]

    After Compline,
    Zaxo

Re: ho w to replace a occurence of string by other string
by holli (Abbot) on Jan 18, 2005 at 14:56 UTC
    this assumes your filenames consist only of a-z, A-Z and _ (which is the meaning of \w) and numbers 0-9 (which is the meaning of \d).

    oneliner: replaces all orrcurences in "infile" and leaves "infile.bak" with the original contents.
    perl -npi.bak -e "s:([\w\d]+\.data):testname/$1:g" infile
    or as a script:
    use strict; $testname="replacement"; open IN, "infile" or die $!; open OUT, ">outfile" or die $!; while ( <IN> ) { s:([\w\d]+\.data):$testname/$1:g print OUT $_; } close IN; close OUT;
    Update:
    As borisz /msg-ed me, \w includes \d. thus [\w\d]is equivavelent to [\w].

    holli, regexed monk
how to modify the text in file
by sachin_chat (Initiate) on Jan 19, 2005 at 06:37 UTC
    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
      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