我是一个长期的读者,第一次提问(请温柔)。
我一直在 Unix Bash 中使用非常混乱的 WHILE READ 来做这件事,但我正在学习 python 并想尝试制作一个更有效的解析器例程。
所以我有一堆日志文件,它们大多是用空格分隔的,但在可能还有空格的地方包含方括号。查找分隔符时如何忽略大括号内的内容?
(我假设 RE 库是必要的)
即样本输入:
[21/Sep/2014:13:51:12 +0000] serverx 192.0.0.1 identity 200 8.8.8.8 - 500 unavailable RESULT 546 888 GET http ://www.google.com/something/fsd?=somegibberish&youscanseethereisalotofcharactershere+bananashavealotofpotassium [somestuff/1.0 (OSX v. 1.0; this_is_a_semicolon; colon:93.1.1) Somethingelse/1999 (COMMA, yep_they_didnt leave_me_a_lot_to_make_this_easy) DoesanyonerememberAOL/1.0]
期望的输出:
'21/Sep/2014:13:51:12 +0000'; 'serverx'; '192.0.0.1'; 'identity'; '200'; '8.8.8.8'; '-'; '500'; 'unavailable'; 'RESULT'; '546'; '888'; 'GET'; 'htp://www.google.com/something/fsd?=somegibberish&youscanseethereisalotofcharactershere+bananashavealotofpotassium'; 'somestuff/1.0 (OSX v. 1.0; this_is_a_semicolon; rev:93.1.1) Somethingelse/1999 (COMMA, yep_they_didnt leave_me_a_lot_to_make_this_easy DoesanyonerememberAOL/1.0'
如果您注意到第一个和最后一个字段(方括号中的字段)仍然有完整的空格。
奖励积分 第 14 个字段 (URL) 始终采用以下格式之一:
htp://google.com/path-data-might-be-here-and-can-contain-special-characters
google.com/path-data-might-be-here-and-can-contain-special-characters
xyz.abc.www.google.com/path-data-might-be-here-and-can-contain-special-characters
google.com:443
- google.com
我想在仅包含域的数据中添加一个附加列(即 xyz.abc.www.google.com 或 google.com)。
到目前为止,我一直在使用带有 IF 语句的 Unix AWK 获取解析后的输出,以用“/”分割该字段并检查第三个字段是否为空白。如果是,则返回第一个字段(直到 : 如果存在),否则返回第三个字段)。如果有更好的方法来做到这一点——最好是在与上述相同的例程中,我很想听听——所以我的最终输出可能是:
'21/Sep/2014:13:51:12 +0000'; 'serverx'; '192.0.0.1'; 'identity'; '200'; '8.8.8.8'; '-'; '500'; 'unavailable'; 'RESULT'; '546'; '888'; 'GET'; 'htp://www.google.com/something/fsd?=somegibberish&youscanseethereisalotofcharactershere+bananashavealotofpotassium'; 'somestuff/1.0 (OSX v. 1.0; this_is_a_semicolon; rev:93.1.1) Somethingelse/1999 (COMMA, yep_they_didnt leave_me_a_lot_to_make_this_easy DoesanyonerememberAOL/1.0'; **'www.google.com'**
脚注:我在示例中将 http 更改为 htp,因此它不会创建一堆分散注意力的链接。