[英]cat, grep and cut - translated to python
也许有足够的问题和/或解决方案,但是我只是无法解决这个问题:我在bash脚本中使用了以下命令:
var=$(cat "$filename" | grep "something" | cut -d'"' -f2)
现在,由于某些问题,我必须将所有代码转换为python。 我以前从未使用过python,而且我完全不知道如何执行postet命令的功能。 有什么想法如何用python解决吗?
您需要更好地了解python语言及其标准库才能翻译表达式
cat“ $ filename” :读取文件cat "$filename"
并将内容转储到stdout
|
:管道将上一个命令的stdout
重定向并将其馈送到下一个命令的stdin
grep的“东西” :搜索与正则表达式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
在Python中,没有外部依赖性,它是这样的(未经测试):
with open("filename") as origin:
for line in origin:
if not "something" in line:
continue
try:
print line.split('"')[1]
except IndexError:
print
您需要使用os.system
模块来执行shell命令
import os
os.system('command')
如果要保存输出以供以后使用,则需要使用subprocess
模块
import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]
您需要在文件行上循环,需要了解字符串方法
with open(filename,'r') as f:
for line in f.readlines():
# python can do regexes, but this is for s fixed string only
if "something" in line:
idx1 = line.find('"')
idx2 = line.find('"', idx1+1)
field = line[idx1+1:idx2-1]
print(field)
并且您需要一种将文件名传递给python程序的方法 ,当您使用它时,也许还需要搜索字符串...
为了将来,请尝试提出更集中的问题,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.