Perl +如何在文件中的单词前添加行

时间:2018-12-18 12:39:11

标签: linux bash shell perl

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

为了将$ info变量的内容添加到文件中的单词– 错误:之前

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:

我在哪里错了?

1 个答案:

答案 0 :(得分:3)

这里的问题是在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