简体   繁体   English

Perl的-p命令行开关有什么作用?

[英]What does Perl's -p command-line switch do?

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

-p-i.bak s//g是什么意思?

  • -p : assume ' while (<>) { ... } ' loop around program and print each processed line too. -p :假设' while (<>) { ... } '循环程序并打印每个处理过的行。
  • -i.bak : change the input file ( filename ) inplace and create the file filename.bak as backup. -i.bak :更改输入文件( filename )inplace并创建文件filename.bak作为备份。
  • s in s/ : to mark substitution s in s/中标记替换
  • g - make the substitution globally..that is don't stop after first replacement. g - 全局替换..在第一次替换后不要停止。

From perlrun : 来自perlrun

-p

causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed: 导致Perl假定你的程序周围有以下循环,这使得它迭代文件名参数有点像sed:

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

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);

See perldoc perlrun. 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. 这个单行将每次出现的search_str更改为文件的每一行中的replace_str ,自动打印生成的行。

The -i.bak switch causes it to change the file in-place and store a backup to another file with the .bak extension. -i.bak开关使其可以就地更改文件,并将备份存储到另一个扩展名为.bak文件中。

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 Perl -p

1.causes perl to assume the following loop around your script, which makes it iterate over filename arguments somewhat like sed: 1.causes perl假设你的脚本周围有以下循环,这使得它迭代文件名参数有点像sed:

  1. Note that the lines are printed automatically. 请注意,线条会自动打印。 To suppress printing use the -n switch. 要禁止打印,请使用-n开关。 A -p overrides a -n switch. -p覆盖-n开关。

link text 链接文字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM