49

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?

2
  • 2
    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
    Oct 30, 2014 at 17:26
  • 7
    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
    Oct 30, 2014 at 17:32

5 Answers 5

105

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
5
  • 1
    This solution seems fine, but ẃhen I urn it I get this attribute-error: AttributeError: 'list' object has no attribute 'split'
    – dnc
    Oct 30, 2014 at 17:36
  • @dncrft: In the final solution, I forgot to index the resultant list from findall. Corrected
    – Abhijit
    Oct 30, 2014 at 17:46
  • 1
    You probably won't need the re.findall. if "something" in line
    – ghostdog74
    Oct 31, 2014 at 1:48
  • @ghostdog74: There is no gurantee from the question that something is not a regex. Generally, grep accepts regex search pattern
    – Abhijit
    Oct 31, 2014 at 3:47
  • 1
    @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
    – gboffi
    Oct 31, 2014 at 21:56
9

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
1
  • 3
    This is more like grep -F than grep, as it does not match a regular expression pattern but a fixed string.
    – Tom Fenech
    Oct 30, 2014 at 17:28
5

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]
1
  • 1
    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
    Oct 30, 2014 at 17:23
3

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,

0
2

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.