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?
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
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
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]
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,
Source: Stackoverflow.com