簡體   English   中英

如何將我的awk命令變成python命令

[英]How do i make my awk command into a python command

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM