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

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

现在,由于一些问题,我必须将所有代码翻译成python.我以前从未使用过python,而且我完全不知道如何实现postet命令的功能.有没有办法用python解决这个问题?

推荐答案

要翻译表达式,需要更好地理解python语言及其标准库

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

|:管道将上一个命令的stdout重定向到下一个命令的stdin

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

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

Linux相关问答推荐

Linux内核中维护进程无关寄存器失败

boost-iostreams 1.59 sparc-solaris 交叉编译失败

在 Bash 中使用 shell 脚本从文件中解析版本号

从父目录中删除目录而不删除父目录 (Linux)

linux 提取字符串中可能是第二常见模式的部分

将文件的一部分插入到另一个文件的特定位置

最小的 x86_64 Hello World ELF 二进制文件是什么?

如何在ubuntu中通过.sh文件启动多个服务

使用 bash 中的数字对 RPM 内核字符串进行版本排序返回不正确的结果

如何重新安装最新的 cmake 版本?

如何计算列的平均值

让 Tk 看起来像一个原生 Linux 应用程序

Linux批量转换:使用转换更改jpg的质量但保留其名称

如何通过 ssh 判断 ubuntu 服务器上是否存在 php 和 apache

为什么 JVM 报告的已提交内存比 linux 进程驻留集大小更多?

在 mac 上通过 ssh 连接到 amazon aws linux 服务器

可以通过 SSH 连接的所有用户的列表

Linux下的签名可执行文件

如何从目录复制内容而不是符号链接?

CentOS:在 PHP 安装中启用 GD 支持