Python/sed获取fi中模式的第一次和最后一次出现之间的数据

2024-06-28 20:37:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要通过日志文件进行解析,然后在文件中找到模式的第一次出现和最后一次出现之间的数据

示例:

cat log1(用于模式tom)

tom dsdsdsd
ssadsds
fdfdf
erdfdf
df  dsfdsd
sfsfsf
dsds dsad
sdsdsd
tom aasasasa
da da dad  
sfsfsadadadad

应给出:

tom dsdsdsd
ssadsds
fdfdf
erdfdf
df  dsfdsd
sfsfsf
dsds dsad
sdsdsd
tom aasasasa

Tags: 文件df模式datomdsdsfdfdfdsad
2条回答

如果文件只包含两个tom,则可以使用sed

sed -n '/tom/,/tom/p'

然而,正如@Andrey所指出的,情况可能并非如此。这很难看,但是再次使用sed

sed -n '/tom/=' file.txt | sed -n '1h;${x;G;s/\n/,/;s/$/p/p}' | xargs -I{} sed -n {} file.txt

可以使用awk(请注意双参数):

awk -v pat='tom' '
# save the first and the last occurrences of the pattern
(ARGIND == 1 && $0 ~ pat){if (!first) first = FNR; last = FNR}
# output everything between the first and the last occurrences of the pattern
(ARGIND == 2 && (FRN >= first || FNR <= last) ){print $0}
# skip the remaining lines
(ARGIND == 2 && FNR > last){exit}
' log.txt log.txt

对于文件中只有两个模式出现的特殊情况,这应该更快:

awk -v pat='tom' '
# detect pattern; if the second occurrence, output the line and exit
($0 ~ pat){if (first++) { print $0 ; exit} }
# output all lines after the first occurrence
(first){print $0}
' log.txt

相关问题 更多 >