【问题标题】:Perl + how to add lines before word in filePerl +如何在文件中的单词之前添加行
【发布时间】:2018-12-18 12:39:11
【问题描述】:

我在我的 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:

我哪里错了?

【问题讨论】:

    标签: linux bash shell perl


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      相关资源
      最近更新 更多