也许有足够多的问题和/或解决方案,但我无法解决这个问题:我在bash脚本中使用了以下命令:
var=$(cat "$filename" | grep "something" | cut -d'"' -f2)
现在,由于一些问题,我必须将所有代码翻译成python.我以前从未使用过python,而且我完全不知道如何实现postet命令的功能.有没有办法用python解决这个问题?
也许有足够多的问题和/或解决方案,但我无法解决这个问题:我在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