tags:

views:

184

answers:

6
perl -p -i.bak -e 's/search_str/replace_str/g' filename

here what is -p -i.bak /s and /g

+1  A: 

1.causes perl to assume the following loop around your script, which makes it iterate over filename arguments somewhat like sed:

  1. Note that the lines are printed automatically. To suppress printing use the -n switch. A -p overrides a -n switch.

link text

pavun_cool
+2  A: 

See perldoc perlrun.

This one-liner changes every occurrence of search_str to replace_str in every line of the file, automatically printing the resulting line.

The -i.bak switch causes it to change the file in-place and store a backup to another file with the .bak extension.

eugene y
+6  A: 

From perlrun:

-p

causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed:

  LINE:
    while (<>) {
        ...             # your program goes here
    } continue {
        print or die "-p destination: $!\n";
    }
Philip Potter
+5  A: 
  • -p: assume 'while (<>) { ... }' loop around program and print each processed line too.
  • -i.bak: change the input file (filename) inplace and create the file filename.bak as backup.
  • s in s/: to mark substitution
  • g - make the substitution globally..that is don't stop after first replacement.
codaddict
Your definition of `-p` is missing the `print` statement. Are you confusing it with `-n`?
Philip Potter
@Philip: Read carefully :P
codaddict
Aha, it's wrong for a different reason then: it doesn't print the input line, it prints the processed line. :P
Philip Potter
@Phillp: Thanks corrected :)
codaddict
+2  A: 

It will automatically read a line from the diamond operator, execute the script, and then print $_.

For more details visit the following link.

Perl -p

kiruthika
+3  A: 

This piece of code:

perl -p -i.bak -e 's/search_str/replace_str/g' filename

Is essentially the same as:

#! /usr/bin/env perl
$extension = '.orig';
LINE:
  while (<>) {
    # -i.bak
    if ($ARGV ne $oldargv) {
      if ($extension !~ /\*/) {
        $backup = $ARGV . $extension;
      } else {
        ($backup = $extension) =~ s/\*/$ARGV/g;
      }
      rename($ARGV, $backup);
      open(ARGVOUT, ">$ARGV");
      select(ARGVOUT);
      $oldargv = $ARGV;
    }

    s/search_str/replace_str/g;

  } continue {
    print;  # this prints to original filename
  }

select(STDOUT);
Brad Gilbert