0

Hey guys I have a question, in my linux I usually grep something in file and print output or print count, How can I do the same in python script. For e.g

Linux Command : grep name filename.txt | wc -l

Python 3.5.2 Command : os.system("grep name filename.txt | wc -l")

This gives me exact result as of linux command, but I need to store this in variable and then print how can I achieve that. Thanks in Advance.

Rob
  • 150
  • 1
  • 4
  • 17
  • 1
    possible duplicate : http://stackoverflow.com/questions/3503879/assign-output-of-os-system-to-a-variable-and-prevent-it-from-being-displayed-on – chenchuk Oct 04 '16 at 15:55

2 Answers2

0

You don't need to call external programs, this would do the equivalent of your command:

import re

pattern = re.compile('name')
with open('filename.txt') as f:
    count = sum(bool(pattern.search(line)) for line in f)
print(count)
mata
  • 67,110
  • 10
  • 163
  • 162
0

Consider:

command1 : grep name filename.txt 
command2 : wc -l

The output of command 1 will be the input for command 2

Syntax in python:

first_output = subprocess.Popen(command 1, shell=True, stdout=subprocess.PIPE)
second_output = subprocess.Popen(command 2,stdin=first_output.stdout,stdout=subprocess.PIPE)
out, err = second_output.communicate()

Example -

p1 = subprocess.Popen("grep name filename.txt", shell=True, stdout=subprocess.PIPE)
p2 = subprocess.Popen("wc -l",stdin=p1.stdout,stdout=subprocess.PIPE)
out, err = p2.communicate()
  • out - output of p2 in text format
  • err - error log, if any
Pierre.Sassoulas
  • 3,733
  • 3
  • 33
  • 48