我怎么把python命令变成awk

2024-09-19 03:44:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个在bash中工作的awk命令,但我现在正试图将它放入python脚本中

我都试过了操作系统,和subprocess.call两者都返回相同的错误。sh:1:语法错误:“”(“意外

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

所以这个awk命令将获取大的inputfile并创建一个输出文件,该文件保留头段的前27行,但从第28行开始,它只每隔10行将其放入输出文件中

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

我也试过了

^{pr2}$

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


Tags: 文件命令脚本bashformatossh错误
2条回答

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)

根据上面的评论,直接使用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')

相关问题 更多 >