没有pcregrep的情况下,如何在文件中找到多行正则表达式的匹配项?
我需要查找/打印每个事件的位置。
不幸的是,pcregrep不存在,我无权安装它。其他替代方法grep
perl
sed
python
等。
要搜索的正则表达式的示例是:
Text\nLine
脚本在几十个文件中提供了数百MB的结构化文本,但不幸的是,由于某些原因,缺少了几行。我确实需要检查那些行是否缺失,从而搜索上一行和下一行的顺序。
Text
Missing //this line is sometimes missing.
Line
可能的输入
example.txt
Text
Missing
Line
Text
Missing
Line
Text
Line
Text
Missing
Line
可能的输出:
example.txt,第10行
一些尝试没有成功:
pcregrep
# command not found
apt-get install pcregrep
# no permission, no su credentials, distro don't provide pcregrep, outdated sources, customer does not want changes on the serve, etc.
sed -r 's#(Text\nLine)#\1#' ./*
# print all lines, not only matches, no indication of file or line, etc.
grep 'Text\nLine' ./*
# Does not works on multi-lines
sed -n '/Text/,/Line/{p}' ./*
# Not the same regex, does not indicate result lines, etc.
Unix工具通常是面向行的,因此无法使用标准工具箱在多行输入中应用正则表达式。
sed
可以以一种能够检测到您要查找的行的方式来处理文件,但是我们严格使用单个行上的操作来做到这一点:
$ sed -n '/^Text/{N;/^Text\nLine/=;D;}' file
10
该sed
脚本Text
在行的开头查找字符串。找到后,它会将下一行添加到其缓冲区中,并\n
在中间插入一行。
如果缓冲区现在匹配,^Text\nLine
则使用中的=
命令输出当前行号sed
。输出的行号是Line
文件中该行的行号。
请注意,尽管第二个正则表达式似乎在文件中的换行符上匹配,但事实并非如此。它在其内部缓冲区中的换行符上匹配,N
当我们从文件中读取下一行时,使用命令将其放在那里。
如果要将其应用于多个文件,则可能会在循环中使用它:
for name in pattern; do
printf 'Processing %s...\n' "$name"
sed -n '/^Text/{N;/^Text\nLine/=;D;}' "$name"
done
其中pattern
是与您感兴趣的文件匹配的普通文件名遍历模式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句