【发布时间】:2020-01-13 08:44:00
【问题描述】:
我有许多目录,其中包含格式如下的文本文件:
class FeatureFE():
meta_data = MetaData(
name='COOL_FEATURE',
sub_type='EXTRA_COOL_FEATURES',
required_data=[accounts, logs],
has_graph=True,
x_axis_label='Time',
y_axis_label='Foo',
graph_caption='Description of my feature',
priority='low',
)
我被赋予的任务是遍历每个.py 文件,如果是has_graph=True,则提取name、required_data 和graph_caption - 最终目标是一个结构如下的CSV:
name, required_data, graph_caption
'COOL_FEATURE', [accounts, logs],'Description of my feature',
这对awk/sed/grep 来说绝对可行,但我很难做到。到目前为止,我已经做到了:
grep -E -B 4 -A 5 "has_graph=True" feature_17.py | tr -s ' ' | grep '^ name\|^ required_data\|^ graph_caption' | sed 's/.*=//'
返回
'COOL_FEATURE',
[accounts, logs],
'Description of my feature',
对于一个文件,但在 *.py 上运行时什么都没有。
非常感谢您的帮助!
【问题讨论】:
-
所需的输出 CSV 标题行
name, required_data, graph_caption是 3 个字段,但数据行'COOL_FEATURE', [accounts, logs],'Description of my feature'是 4 个字段(计算逗号)。您需要将每个字段括在双引号中,因此还需要将每个字段中可能出现的任何双引号加倍(您应该在示例中包含它)以使输出成为有效的 CSV。
标签: perl awk sed grep text-processing