kentcdodds
kentcdodds

Reputation: 29031

Find and replace in a file without reading file as a string

My Question: If I'm given C:\text_file.txt as a parameter on the command line when my PERL script is called and the text_file.txt contains the text "Hello World World World", how do I replace all instances of "World" with "Earth"?

I'm new to PERL. I'm writing a script which accepts a parameter of a filepath. I want to do a find replace on the contents of the file. I know I could do something like this: $string =~ s/World/Earth/g; but I don't want to read the file into a string if I can help it. Is there a way to do this directly on the file without reading it in as a string? Thanks!

Upvotes: 1

Views: 1676

Answers (1)

Sean
Sean

Reputation: 29772

This is what Perl's -i ("inplace edit") switch is for:

$ perl -i.bak -pe 's/World/Earth/g' text_file.txt

EDIT: To incorporate this identical functionality into a larger Perl script:

{
    local $^I = '.bak';
    local @ARGV = ('text_file.txt');
    local $_;
    while (<>) {
        s/World/Earth/g;
        print;
    }
}

The $^I variable reflects the value of the -i command-line switch; here, it's being set manually. Also, @ARGV is being manually set to the list of files that would ordinarily be taken from the command line. The whole thing is wrapped in a block so that $^I and @ARGV, set with local, resume their original values afterwards; this may not be strictly necessary, depending on the rest of the program. I also localized $_ just to keep the while loop from clobbering the value it previously held; this also may not be necessary.

Note that you can use just -i instead of -i.bak from the command line if you want to avoid creating a backup file. The corresponding code would be $^I = "" instead of $^I = '.bak'.

Upvotes: 4

Related Questions