[python] cat, grep and cut - translated to python

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?

This question is related to python linux bash grep cut

The answer is


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,


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to grep

grep's at sign caught as whitespace cat, grep and cut - translated to python How to suppress binary file matching results in grep Linux find and grep command together Filtering JSON array using jQuery grep() Linux Script to check if process is running and act on the result grep without showing path/file:line How do you grep a file and get the next 5 lines How to grep, excluding some patterns? Fast way of finding lines in one file that are not in another?

Examples related to cut

Loop through a comma-separated shell variable cat, grep and cut - translated to python How to find the last field using 'cut' Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it? Using cut command to remove multiple columns how to remove the first two columns in a file using shell (awk, sed, whatever) How can I remove the extension of a filename in a shell script? bash script use cut command at variable and store result at another variable How to specify more spaces for the delimiter using cut? Copy and paste content from one file to another file in vi