简体   繁体   English

Perl 在命令行中: perl -p -i -e “some text” /path

[英]Perl in command line: perl -p -i -e “some text” /path

I am not familiar with perl.我对 perl 不熟悉。 I am reading an installation guide atm and the following Linux command has come up:我正在阅读安装指南 atm 并且出现了以下 Linux 命令:

perl -p -i -e "s/enforcing/disabled/" /etc/selinux/config

Now, I am trying to understand this.现在,我试图理解这一点。 Here is my understanding so far:到目前为止,这是我的理解:

-e simply allows for executing whatever follows -e 只允许执行以下任何内容

-p puts my commands that follow -e in a loop. -p 将我跟在 -e 之后的命令放在一个循环中。 Now this is strange to me, as to me this command seems to be trying to say: Write "s/enforcing/disabled/" into /etc/selinux/config.现在这对我来说很奇怪,因为对我来说这个命令似乎是想说:将“s/enforcing/disabled/”写入/etc/selinux/config。 Then again, where is the "write" command?再说一次,“写”命令在哪里? And what is this -i (inline) good for?这 -i (内联)有什么用?

-p changes -p改变

s/enforcing/disabled/

to something equivalent to相当于

while (<>) {
   s/enforcing/disabled/;
   print;
}

which is short for这是缩写

while (defined( $_ = <ARGV> )) {
   $_ =~ s/enforcing/disabled/;
   print($_);
}

What this does:这是做什么的:

  1. It reads a line from ARGV into $_ .它将ARGV中的一行读入$_ ARGV is a special file handle that reads from the each of the files specified as arguments (or STDIN if no files are provided). ARGV是一个特殊的文件句柄,它从指定为 arguments 的每个文件中读取(如果没有提供文件,则为 STDIN)。
  2. If EOF has been reached, the loop and therefore the program exits.如果已达到 EOF,则循环并因此程序退出。
  3. It replaces the first occurrence of enforcing with disabled .它将第一次出现的enforcing替换为disabled
  4. It prints out the modified line to the default output handle.它将修改后的行打印到默认的 output 句柄。 Because of -i , this is a handle to a new file with the same name as the one from which the program is currently reading.*因为-i ,这是一个新文件的句柄,它与程序当前正在读取的文件同名。*
  5. Repeat.重复。

For example,例如,

$ cat a
foo
bar enforcing the law
baz
enforcing enforcing

$ perl -pe's/enforcing/disabled/' -i a

$ cat a
foo
bar disabled the law
baz
disabled enforcing

* — In old versions of Perl, the old file has already been deleted at this point, but it's still accessible as long as there's an open file handle to it. * — 在旧版本的 Perl 中,此时旧文件已被删除,但只要有打开的文件句柄,它仍然可以访问。 In very new versions of Perl, this writes to temporary file that will later overwrite the file from which the program is reading.在非常新的 Perl 版本中,这将写入临时文件,该文件稍后将覆盖程序正在读取的文件。

To find out exactly what Perl is going to do, you can use the O module确切了解 Perl 将要做什么,您可以使用O模块

perl -MO=Deparse -p -i -e "s/enforcing/disabled/" file

outputs输出

BEGIN { $^I = ""; }
LINE: while (defined($_ = readline ARGV)) {
    s/enforcing/disabled/;
}
continue {
    die "-p destination: $!\n" unless print $_;
}
-e syntax OK

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

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