programminglearner
programminglearner

Reputation: 542

Python SubProcess For Awk

I am trying to use this awk command in Python with subprocess but I am not sure how I can do the double pipe. I would rather not use shell=True as it's poor practice. I have been able to incorporate other awk commands but none of them required double pipe.

awk 'FNR==NR{if($0~/name: /){line=FNR};next} FNR<=line || FNR>(line+4)' file.txt file.txt

This removes 4 lines after the last occurrence of "name". Here is the content of my file originally:

name: file1
name: file2
name: file3




file4
file5
file6

Running this command in the terminal will return:

name: file1
name: file2
name: file3
file4
file5
file6

I am trying to use python subprocess to do this from within a python file but I'm not sure how to.

Here is my initial approach:

import os
import sys
import subprocess as sb

sb.Popen('awk','FNR==NR{if($0~/name: /){line=FNR};next} FNR<=line || FNR>(line+4)','file.txt','file.txt')

This is the error I get:

TypeError: bufsize must be an integer

Any help on how to do this WITHOUT shell=True?

Upvotes: 0

Views: 68

Answers (1)

You need to put the arguments for the command in a list ([]), or they'll end up being assigned to bufsize, executable, etc. instead of where you want them to go:

sb.Popen(['awk','FNR==NR{if($0~/name: /){line=FNR};next} FNR<=line || FNR>(line+4)','file.txt','file.txt'])

It has nothing to do with ||.

Upvotes: 1

Related Questions