linux - 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:
我在这里错在哪里?
解决方案
这里的问题是,在 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
推荐阅读
- php - 我通过 php 标头强制下载的速度太慢,无法用于商业用途
- excel - 如何将列表参数传递给 Excel 中的 ODBC 查询(Microsoft Query)
- r - 如何使选定的表仅限于矩阵而不是运行列表?
- android - Android:根据用户设置以编程方式更改 SourceSet
- excel - VBA - 从所有模块受密码保护的工作簿中运行宏
- javascript - Cypress.io:如何创建有助于根据输入选择不同 DOM 元素的函数
- html - 如何让我的表单从页面顶部开始?每当单击“下一步”按钮时,都会一直滚动到底部
- c# - 密码类型 InputField 的文本只有星号
- excel - EXCEL:在将数据粘贴到 Excel 时自动调整列宽
- powershell - PowerShell 比较输出