cat、grep 和 cut - 翻译成 python [英] cat, grep and cut - translated to python

查看:36
本文介绍了cat、grep 和 cut - 翻译成 python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许有足够的问题和/或解决方案,但我无法解决这个问题:我在bash脚本中使用了以下命令:

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)    

现在,由于一些问题,我必须将所有代码翻译成 python.我以前从未使用过 python,我完全不知道如何执行 postet 命令.任何想法如何用 python 解决这个问题?

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?

推荐答案

你需要对python语言及其标准库有更好的理解才能翻译表达式

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

cat "$filename":读取文件 cat "$filename" 并将内容转储到标准输出

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

|:管道重定向来自上一个命令的stdout,并将其提供给下一个命令的stdin

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

grep "something":搜索正则表达式something纯文本数据文件(如果指定)或在标准输入中并返回匹配的行.

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

cut -d'"' -f2:使用特定的分隔符和特定的索引/拼接分割字符串结果列表中的字段

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

Python 等价物

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)

结合

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

这篇关于cat、grep 和 cut - 翻译成 python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆