What does the Perl -p command line switch do?

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

What do -p , -i.bak s/ and /g mean?

+4
source share
6 answers
  • -p : suppose ' while (<>) { ... } ' combine the program and print each line that has also been processed.
  • -i.bak : change the input file ( filename ) in place and create the file filename.bak as a backup.
  • s in s/ : mark substitution
  • g - make the replacement globally .. it does not stop after the first replacement.
+13
source

From perlrun :

-p

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

  LINE: while (<>) { ... # your program goes here } continue { print or die "-p destination: $!\n"; } 
+8
source

This piece of code:

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

Essentially, this is 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); 
+3
source

See perldoc perlrun.

This single-line font changes each occurrence from search_str to replace_str in each line of the file, automatically printing the resulting line.

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

+2
source

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

See the following link for details.

Perl -p

+2
source

1. calls perl to take the following loop around your script, which causes it to iterate over the arguments in the file name somewhat like sed:

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

link text

+1
source

Source: https://habr.com/ru/post/1304561/


All Articles