【问题标题】:How do i make my awk command into a python command我如何将我的 awk 命令变成 python 命令
【发布时间】:2019-04-12 16:37:08
【问题描述】:

我有一个在 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)')

两者都出现了上述相同的错误。我错过了什么?

【问题讨论】:

  • 你不能直接在python中做你想做的事吗?

标签: python awk


【解决方案1】:

您的 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)

【讨论】:

    【解决方案2】:

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

    但是,如果您想使用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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      相关资源
      最近更新 更多