我尝试读取一个 txt 文件并查找包含特定单词“checkout_revision”的行。我想在 for 循环中逐行查找这些行并将它们存储在我的变量中,比如说 temp。我听说grep
withcut
适合这样做。但是我做不到。有谁能帮我吗?这是我的代码:
for line in intersect:
cmd=""" grep "CHECKOUT_REVISION" |cut -d\'\"\' -f2"""%fst_directory
cmd_test=os.system(cmd)
答案1
假设有一个文件/home/eday/test.txt
,其内容如下:
this is a test
another line
CHECKOUT_REVISION this must be stored
some other things
CHECKOUT_REVISION another line to store
以下 Python 脚本将读取存储在my_file
变量中的文件,查找存储在look_for
变量中的内容,如果找到匹配项,它将把它存储在temp
变量(列表变量)中。
最后它将打印到输出的内容temp
您可以注释掉或者删除打印行。
#!/usr/bin/env python
# path to the file to read from
my_file = "/home/eday/test.txt"
# what to look in each line
look_for = "CHECKOUT_REVISION"
# variable to store lines containing CHECKOUT_REVISION
temp = []
with open(my_file, "r") as file_to_read:
for line in file_to_read:
if look_for in line:
temp.append(line)
# print the contents of temp variable
print (temp)
上述脚本将在终端中有以下输出:
$ ['CHECKOUT_REVISION this must be stored', 'CHECKOUT_REVISION another line to store']
答案2
result = []
for line in open('filename'):
if 'CHECKOUT_REVISION' in line:
result.append(line.split('\'"\'')[1])
我想这就是你想要的 - 你得到一个字符串列表,其中每行的第二个字段包含字符串CHECKOUT_REVISION
。问题应该转移到堆栈溢出尽管。
答案3
受到以上答案的启发,这里是命令行版本。
#!/usr/bin/env python
import sys
pattern = sys.argv[1]
fileName = sys.argv[2]
count=0
temp = []
with open(fileName, "r") as file_to_read:
for line in file_to_read:
if pattern in line:
#IN case you want to have number of hits
count=count+1
temp.append(line)
for i in range(count):
print (temp[i].rstrip())
像这样运行它:
python "pattern" thisScript.py
答案4
我同意斯蒂夫的回答是一个很好的答案,但如果你仍然想在 python 中使用grep
或cut
(或其他)来自 bash 的命令,我建议你不要使用os.system
,而是使用subprocess
模块。例如:
#!/usr/bin/env python
import subprocess
cmd = "grep CHECKOUT_REVISION /home/eday/test.txt | cut -d'\"' -f2 -s"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
temp = process.communicate()[0]
print (temp)
如果/home/eday/test.txt
文件是这样的:
some lines
CHECKOUT_REVISION="revision one"
some other lines
CHECKOUT_REVISION="revision two"
other lines
上述 Python 脚本的输出将是:
revision one
revision two