【发布时间】:2019-07-03 22:37:21
【问题描述】:
如果我将myfile 带到python 可用的环境中,我可以运行以下命令:
cat myfile | python filter.py
filter.py
import sys
results = []
for line in sys.stdin:
results.append(line.rstrip("\n\r"))
start_match = "some text"
lines_to_include_before_start_match = 4
end_match = "some other text"
lines_to_include_after_end_match = 4
for line_number, line in enumerate(results):
if start_match in line:
for x in xrange(line_number-lines_to_include_before_start_match, line_number):
print results[x]
print line
for x in xrange(line_number+1, len(results)):
if end_match in results[x]:
print results[x]
for z in xrange(x+1, x+lines_to_include_after_end_match):
print results[z]
break
else:
print results[x]
print ""
但是我想运行它的环境没有 python。将其转换为我知道环境中存在的 perl 是我唯一的选择吗?是否有简单的 sed 或 awk 命令来执行此操作?
我尝试了以下方法,但由于它错过了 +/- 4 行,因此并不能完全满足我的需求:
cat myfile | sed -n '/some text/,/some other text/p'
[编辑:python 脚本说lines_to_include_after_end_match 是4,但实际上它返回3]
【问题讨论】: