如何将awk命令转换为python命令

时间:2019-04-12 16:37:08

标签: python awk

我有一个可以在bash中运行的awk命令,但是我现在正尝试将其放入python脚本中

我已经尝试了os.system和subprocess.call都返回相同的错误。 sh:1:语法错误:“(”意外

os.system('awk \'FNR<=27{print;next} ++count%10==0{print;count}\' \'{0} > {1}\'.format(inputfile, outpufile)')

因此,这个awk命令将采用较大的输入文件,并创建一个输出文件,该文件保留标题的前27行,但随后从第28行开始,它仅需占用第10行并将其放入输出文件中

我使用.format()是因为它在python脚本中,因此每次运行时输入文件都会不同。

我也尝试过

subprocess.call('awk \'FNR<=27{print;next} ++count%10==0{print;count}\' \'{0} > {1}\'.format(inputfile, outpufile)')

都出现了与上面相同的错误。我想念什么?

2 个答案:

答案 0 :(得分:0)

根据上面的评论,直接使用python的Python可能更多(更易于管理)。

但是,如果要使用awk,则一种方法是分别使用变量文件名来格式化命令。

这可以在基本的测试文本文件中使用:

import os


def awk_runner(inputfile, outputfile):
    cmd = "awk 'FNR<=27{print;next} ++count%10==0{print;count}' " + inputfile + " > " + outputfile
    os.system(cmd)


awk_runner('test1.txt', 'testout1.txt')

答案 1 :(得分:0)

您的Python代码有两个主要问题:

  1. format()是一个python方法调用,不应将其放入awk_cmd字符串中以在shell下执行
  2. 调用format()方法时,大括号{}用于标识格式字符串对象中的替换目标,需要使用{{ ... }}来对它们进行转义

请参见下面的代码修改版本:

awk_cmd = "awk 'FNR<=7{{print;next}} ++count%10==0{{print;count}}' {0} > {1}".format(inputfile, outpufile)
os.system(awk_cmd)