Accessing a file and modifying the contents

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • keirnna
    New Member
    • Jan 2007
    • 5

    Accessing a file and modifying the contents

    I am trying to access a file with perl and use substitution on that files contents and print the result of that substitution.

    I also need the the file I am accessing to be input on the command line like this: keirnna$ perl_script.pl file.txt

    Here is what I have so far:

    #!/usr/bin/perl -w

    open(INPUT, "+<", "/pretend/path/file.txt")
    or die "Couldn't open file..txt for reading: $!\n";
    while (<INPUT>) {
    $_ =~ s/really/REALLY/gi;
    print;
    }
    close(INPUT);

    However all I can get this to do is print the original file and as you can see I am forcing the use of file.txt in the script instead of naming it when I execute the program. I did a lot of searching and reading, but I haven't stumbled upon a solution yet. Sorry if this is a newb question.
  • keirnna
    New Member
    • Jan 2007
    • 5

    #2
    Actually I see now that it is printing the edited file now all I need to do is figure out how to make the unix command: perl_sript.pl text.txt to edit text.txt.

    Comment

    • miller
      Recognized Expert Top Contributor
      • Oct 2006
      • 1086

      #3
      As a one-liner:

      Code:
      perl -pi -e "s/really/REALLY/gi" /pretend/path/file.txt

      Comment

      • keirnna
        New Member
        • Jan 2007
        • 5

        #4
        Thanks but I need it to be a script and not a one liner.

        Comment

        • miller
          Recognized Expert Top Contributor
          • Oct 2006
          • 1086

          #5
          Then I would suggest you use two things:


          http://perldoc.perl.org/perlvar.html - Search for @ARGV

          I would write it for you in a couple minutes, but those are all the links that you need and I need to go to bed.

          Post if you have any problems.

          Comment

          • KevinADC
            Recognized Expert Specialist
            • Jan 2007
            • 4092

            #6
            since I have nothing to do at the moment:

            Code:
            #!/usr/bin/perl -w
            
            my $file = $ARGV[0] || die "no file entered on command line";
            
            {
               local @ARGV = ($file);
               local $^I = '.bac';
               while (<>) {
                  s/really/REALLY/gi;
                  print;
               }
            }
            print "finished";
            although it's odd that you are using the "i" option unless you are looking for possible mixed-case matches of "really" instead of all lower-case. "i" tells perl to ignore case in the search pattern.

            Comment

            Working...