cat, grep and cut - translated to python

114,727

Solution 1

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 re
with 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

Solution 2

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

Solution 3

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

import os
os.system('command')

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

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

Solution 4

You need a loop over the lines of a file, you need to learn about string methods

with open(filename,'r') as f:
    for line in f.readlines():
        # python can do regexes, but this is for s fixed string only
        if "something" in line:
            idx1 = line.find('"')
            idx2 = line.find('"', idx1+1)
            field = line[idx1+1:idx2-1]
            print(field)

and you need a method to pass the filename to your python program and while you are at it, maybe also the string to search for...

For the future, try to ask more focused questions if you can,

Solution 5

For Translating the command to python refer below:-

1)Alternative of cat command is open refer this. Below is the sample

>>> f = open('workfile', 'r')
>>> print f

2)Alternative of grep command refer this

3)Alternative of Cut command refer this

Share:
114,727

Related videos on Youtube

dnc
Author by

dnc

Updated on February 24, 2020

Comments

  • dnc
    dnc about 4 years

    maybe there are enough questions and/or solutions for this, but I just can't help myself with this one question: I've got the following command I'm using in a bash-script:

    var=$(cat "$filename" | grep "something" | cut -d'"' -f2)    
    

    Now, because of some issues I have to translate all the code to python. I never used python before and I have absolutely no idea how I can do what the postet commands do. Any ideas how to solve that with python?

    • Tom Fenech
      Tom Fenech over 9 years
      You asked for feedback, so I provided it. Your question is more or less "write me some python to do this" without showing any effort yourself or where you got stuck. If you tried and failed, then people will be more likely to want to help you and less likely to downvote if you include your efforts and show where you got stuck.
    • Tom Fenech
      Tom Fenech over 9 years
      Maybe lose the bad attitude as well, people are trying to help you. Dumping a load of failed attempts in a question is no more useful than simply asking for the answer. You need to make it clear what you don't understand and ask a clear, focused question, then you will rightfully be upvoted.
  • Tom Fenech
    Tom Fenech over 9 years
    You have not shown how to implement the commands in python, you have shown how to call the commands from python. Presumably, that is why you have been downvoted.
  • Tom Fenech
    Tom Fenech over 9 years
    This is more like grep -F than grep, as it does not match a regular expression pattern but a fixed string.
  • dnc
    dnc over 9 years
    This solution seems fine, but ẃhen I urn it I get this attribute-error: AttributeError: 'list' object has no attribute 'split'
  • Abhijit
    Abhijit over 9 years
    @dncrft: In the final solution, I forgot to index the resultant list from findall. Corrected
  • ghostdog74
    ghostdog74 over 9 years
    You probably won't need the re.findall. if "something" in line
  • Abhijit
    Abhijit over 9 years
    @ghostdog74: There is no gurantee from the question that something is not a regex. Generally, grep accepts regex search pattern
  • gboffi
    gboffi over 9 years
    @Abhijit I really appreciated your answer, except for one small problem: your python equivalent for cut is off by one, as in printf 'dummy "target" missed' | cut -d'"' -f2 -> target vs python -c "print 'dummy \"target\" missed'.split('\"')[2]" -> [space]missed. Ciao from