简体   繁体   English

函数中的Python子流程awk命令,将列表中的元素作为参数

[英]Python subprocess awk command in a function, taking element from list as argument

I want to subprocess an awk command with a list element as argument. 我想用列表元素作为参数对awk命令进行子处理。

With a single argument, and from a shell prompt, it's prety simple: 仅需一个参数,并且在shell提示符下,操作起来非常简单:

$ awk -F "," '/US/ && /00001/ {print $1","$3}' stock_inventory.csv  > pretest_00001.csv

So using a list, I put it all in a Python script like: 因此,使用列表,我将其全部放入Python脚本中,例如:

import subprocess

mylist = [00001, 00002, 00003]

def myawk(item_code):
    subprocess.call("awk -F "," '/US/ && /%d/ {print $1","$3}' stock_inventory.csv  > pretest_%d.csv") % item_code

for i in mylist:
    myawk(i)

I did it wrong somewhere. 我在某处做错了。 Could Popen have been of any help? Popen对您有帮助吗? What about lambda in this case? 那么在这种情况下,lambda呢?

Thanks for you help. 感谢您的帮助。

perhaps ditch python and do all in awk ? 也许抛弃python并全部在awk

$ awk 'BEGIN{FS=OFS=",";
             n=split("00001,00002,00003",item)}
       /US/ {for(i=1;i<=n;i++) 
               if($0~item[i]) 
                 print $1,$3 > "pretest_"item[i]".csv"}' stock_inventory.csv  

Thanks all for your help. 感谢你的帮助。

I found a more elegant way to resolve it, though it's not through a Python script but a Bash one instead. 我找到了一种更优雅的解决方法,尽管它不是通过Python脚本,而是通过Bash脚本。

#!/bin/bash

declare -a arr=("00001" "00002" "00003")

for i in "${arr[@]}"

do

    cat stock_inventory.csv | grep $i | grep US | awk -F "," '{print $1","$3}' > pretest_$i.csv

done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM