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

查看:183
本文介绍了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纯文本数据文件( (如果已指定)或在stdin中返回匹配的行.

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天全站免登陆