使用 sed 或 perl 在每个否定环视的特定行添加反斜杠

问题描述 投票:0回答:1

在我们高效的 Splunk 环境中,我们在一个特殊的应用程序中拥有一百多个自行开发的用例,我们希望将其进一步导出到专用于其他客户等的集群。 Savedsearches.conf 分为默认文件夹和本地文件夹,我们希望通过

splunk btool --app=our_fancy_usecases savedsearches list > searches.conf
预先合并这些文件夹。由此产生的配置文件将如下所示:

[Stanza #1]
some.config = some settings
description = just a few words
some.other.config = more settings
search = this is 
| a well
| formatted search
[Stanza #2]
some.config = 1
description = This is taking 
a lot of words
to explain
this time.
some.other.config = 2
search = a lot 
of searching 
to do
[This is yet another stanza]
the.end = nigh

该 btool 的问题是丢失了原始配置文件中的反斜杠(“”),这些反斜杠显示特定行实际上是多行值。每个设置都可以是多行值,但不一定需要如此。当反斜杠丢失时,Splunk 将仅读取该设置的配置,直到行结束,即,对于第一个节,Splunk 中的搜索最终将仅为

this is
,缺少以下两行。也就是说,配置文件应该如下所示:

[Stanza #1]
some.config = some settings
description = just a few words
some.other.config = more settings
search = this is \
| a well\
| formatted search
[Stanza #2]
some.config = 1
description = This is taking \
a lot of words\
to explain\
this time.
some.other.config = 2
search = a lot \
of searching \
to do
[This is yet another stanza]
the.end = nigh

遗憾的是,btool 缺乏保留这些反斜杠的功能,所以我试图用 sed 或任何可以完成这项工作的工具将它们恢复。

我首先研究如何使用正则表达式获取需要更改的行。节始终包含在方括号

[
]
中,并且设置始终在
=
后面有一个空格,在实际值之前还有另一个空格。我想出了这个负面的看法:
\n(?!^[A-Za-z0-9._]+ = .*$|^\[.*\])
对于顶部的配置示例,这似乎很好地抓住了我想在 regex101 中更改的内容。然而#sed 不允许环视。 #Perl 应该是一个选择,但这就是我失败的地方:

perl -pe 's/\n(?![A-Za-z0-9._]+ = .*$|\[.*\]$)/\\\n/' test.conf > test.out ; cat test.out

[Stanza #1]\
some.config = some settings\
description = just a few words\
some.other.config = more settings\
search = this is\
| a well\
| formatted search\
[Stanza #2]\
some.config = 1\
description = This is taking\
a lot of words\
to explain\
this time.\
some.other.config = 2\
search = a lot\
of searching\
to do\
[This is yet another stanza]\
the.end = nigh\

遗憾的是,这根本无法按预期工作,只是在每一行添加一个反斜杠。我也用#sed 摆弄了一下:

sed '/^[A-Za-z0-9._]\+ = .*$\|^\[.*\]$/! s/.*/&\\/' test.conf > test.out ; cat test.out
[Stanza #1]
some.config = some settings
description = just a few words
some.other.config = more settings
search = this is
| a well\
| formatted search\
[Stanza #2]
some.config = 1
description = This is taking
a lot of words\
to explain\
this time.\
some.other.config = 2
search = a lot
of searching\
to do\
[This is yet another stanza]
the.end = nigh

关于如何实现我的目标有什么想法吗?

regex linux bash perl
1个回答
0
投票
perl  -ne 'chomp;
           print "\\" if ! / = |^\[/;
           print "\n" if $. != 1;
           print;
           END { print "\n" }' < file
  • -n
    逐行读取输入并运行每行代码;
  • chomp 从输入中删除最后的换行符;
  • 如果“下”行不是设置或节,则打印反斜杠;
  • 除了第一行之前打印换行符;
  • 打印“下一行”;
  • 最后打印换行符。
© www.soinside.com 2019 - 2024. All rights reserved.