首页 > 解决方案 > Perl +如何在文件中的单词之前添加行

问题描述

我在我的 bash 脚本中编写了以下代码(在 redhat 7.2 版本上运行)

为了在单词之前添加 $info 变量的内容 – ERROR: in file

export info="The Postfix error(8) delivery agent processes delivery requests from the queue manager. Each request specifies a queue file, a sender address, the reason for non-delivery (specified as the next-hop destination), and recipient"
perl -i -plne 'print "$ENV{info}" if(/ERROR:/);' file

运行代码后,我们可以看到文件的输出太长,最好将行分隔为 3 行

more file

The Postfix error(8) delivery agent processes delivery requests from the queue manager. Each request specifies a queue file, a sender address, the reason for non-delivery (specified as the next-hop destination), and recipient
ERROR:

所以我在信息行中添加“\n”如下:然后我们再次运行代码

export info="The Postfix error(8) delivery agent processes delivery requests from the queue manager. \nEach request specifies a queue file, a sender address, \nthe reason for non-delivery (specified as the next-hop destination), and recipient"
perl -i -plne 'print "$ENV{info}" if(/ERROR:/);' file

但文件仍然不包含新行(实际上“\n”在行中)

The Postfix error(8) delivery agent processes delivery requests from the queue manager. \nEach request specifies a queue file, a sender address, \nthe reason for non-delivery (specified as the next-hop destination), and recipient
ERROR:

而预期结果应该是:

The Postfix error(8) delivery agent processes delivery requests from the queue manager. 
Each request specifies a queue file, a sender address, 
the reason for non-delivery (specified as the next-hop destination), and recipient
ERROR:

我在这里错在哪里?

标签: linuxbashshellperl

解决方案


这里的问题是,在 Bash 中,双引号不会导致\n被解释为换行符。

为此,我想我只会在字符串中包含文字换行符:

export info="The Postfix error(8) delivery agent processes delivery requests from the 
queue manager.
Each request specifies a queue file, a sender address,
the reason for non-delivery (specified as the next-hop destination), and recipient"
perl -i -plne 'print "$ENV{info}" if(/ERROR:/);' file

否则,您可以使用printf,但这似乎有点矫枉过正:

export info=$(printf "The Postfix error(8) delivery agent processes delivery requests from the queue manager. \nEach request specifies a queue file, a sender address, \nthe reason for non-delivery (specified as the next-hop destination), and recipient")
perl -i -plne 'print "$ENV{info}" if(/ERROR:/);' file

推荐阅读