cat, grep and cut - translated to python cat, grep and cut - translated to python bash bash

cat, grep and cut - translated to python


You need to have better understanding of the python language and its standard library to translate the expression

cat "$filename": Reads the file cat "$filename" and dumps the content to stdout

|: pipe redirects the stdout from previous command and feeds it to the stdin of the next command

grep "something": Searches the regular expressionsomething plain text data file (if specified) or in the stdin and returns the matching lines.

cut -d'"' -f2: Splits the string with the specific delimiter and indexes/splices particular fields from the resultant list

Python Equivalent

cat "$filename"  | with open("$filename",'r') as fin:        | Read the file Sequentially                 |     for line in fin:                      |   -----------------------------------------------------------------------------------grep 'something' | import re                                 | The python version returns                 | line = re.findall(r'something', line)[0]  | a list of matches. We are only                 |                                           | interested in the zero group-----------------------------------------------------------------------------------cut -d'"' -f2    | line = line.split('"')[1]                 | Splits the string and selects                 |                                           | the second field (which is                 |                                           | index 1 in python)

Combining

import rewith open("filename") as origin_file:    for line in origin_file:        line = re.findall(r'something', line)        if line:           line = line[0].split('"')[1]        print line


In Python, without external dependencies, it is something like this (untested):

with open("filename") as origin:    for line in origin:        if not "something" in line:           continue        try:            print line.split('"')[1]        except IndexError:            print


you need to use os.system module to execute shell command

import osos.system('command')

if you want to save the output for later use, you need to use subprocess module

import subprocesschild = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)output = child.communicate()[0]