微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

cat,grep和cut-翻译成python

如何解决cat,grep和cut-翻译成python

您需要更好地了解python语言及其标准库才能翻译表达式

cat“ $ filename”:读取文件cat "$filename"并将内容转储到stdout

|:管道将上stdout一条命令重定向,并将其馈送到stdin下一条命令的

grep“ something”搜索正则表达式something纯文本数据文件(如果已指定)或在stdin中,并返回匹配的行。

cut -d’“’-f2:使用特定的定界符分割字符串,并从结果列表中索引/拼接特定字段

相当于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

解决方法

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

var=$(cat "$filename" | grep "something" | cut -d'"' -f2)

现在,由于某些问题,我必须将所有代码转换为python。我以前从未使用过python,而且我完全不知道如何执行postet命令的功能。有什么想法如何用python解决吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。