【问题】
Hi friends, I want to ask a question:
how can I extract all the text between two given strings str1 and str2? The returned results should be seperated by something such as a space line.
For example, my "input.txt" is:
abdeb ..... str1 aaaaaaaaaaaaaaaaa str2 bbbbbbbbbbbb str1 cccccccccccccccccc str2 ddddddddddddddddd ....
Then my output.txt should be:
aaaaaaaaaaaaaaaaa
cccccccccccccccccc
Note that the text between str1 and str2 could be any length.
I think regular expression and egrep should be able to achieve this, but I am not familar with them. Hope anyone can help. Thanks!
【回答】
正则表达式可以解决这种问题,只是对于初学者来说太抽象不太容易掌握。这种较简单的情况也可以试试采用SPL,SPL既支持正则表达式,也支持直观的函数,比如:pos(取位置)、mid(按位置截取)。比如这个问题的脚本如下:
| A | |
| 1 | =file("D:\\input.txt").read().split("str2") |
| 2 | =A1.select(pos(~,"str1")) |
| 3 | =A2.(mid(~,pos(~,"str1")+4)) |
| 4 | =file("D:\\output.txt").write(A3) |
A1:读取文本串,并按照”str2”分隔成序列
A2:选取含有”str1”子串的成员
A3:从A2的每个成员中截取”str1”后面的字符串
A4:将A3写入output.txt
本文介绍如何利用正则表达式和SPL语言从文件中提取两字符串间的所有文本。例如,输入文件'input.txt'包含特定格式的数据,通过运行SPL脚本,可以生成'output.txt',其中只包含str1和str2之间的文本,每段之间用空行分隔。
686

被折叠的 条评论
为什么被折叠?



