【发布时间】:2015-10-06 18:00:20
【问题描述】:
我翻译了这个 bash one-liner:
awk '/\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1' filename2 > filename1
进入这个 Python 代码
with open('filename1', 'w') as f:
call(['awk', '/\\\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1', 'filename2'], stdout=f)
然而,输出文件是空的,而且在我使用 bash 时也不是。
有了这个:
call(['awk', r"'/\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1'"], stdout=f)
我明白了
awk: '/]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print 前; pno=0} 1' awk: ^ 表达式中的无效字符 '''
示例输入文件:
Interval: [ some_value some_value1]:
Interval: [ some_value some_value2]:
some text here1
some text here2
some text here3
some text here4
Interval: [ some_value some_value3]:
Interval: [ some_value some_value4]:
Interval: [ some_value some_value5]:
Interval: [ some_value some_value6]:
some text here5
some text here6
some text here7
some text here8
Interval: [ some_value some_value7]:
Interval: [ some_value some_value8]:
示例输出文件:
Interval: [ some_value some_value2]:
some text here1
some text here2
some text here3
some text here4
Interval: [ some_value some_value6]:
some text here5
some text here6
some text here7
some text here8
【问题讨论】:
-
对于这种字符串,使用原始字符串表示法:
r"abc\def"。它可以防止错误,并会降低理解您所写内容的整体复杂性。
标签: python awk subprocess