cae*_*sar 3 python command-line grep
我尝试读取 txt 文件并找到包含某个单词“checkout_revision”的行。我想在 for 循环中逐一找到这些行并将它们存储在我的变量中,比如说 temp。听说grepwithcut适合这个。然而我却做不到。有人可以帮助我吗?这是我的代码:
for line in intersect:
cmd=""" grep "CHECKOUT_REVISION" |cut -d\'\"\' -f2"""%fst_directory
cmd_test=os.system(cmd)
Run Code Online (Sandbox Code Playgroud)
假设有一个/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
Run Code Online (Sandbox Code Playgroud)
以下Python脚本将读取存储在my_filevariable中的文件,查找存储在look_forvariable中的内容,如果找到匹配项,则会将其存储在tempvariable中,该文件是一个列表变量。
最后它将打印到输出的内容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)
Run Code Online (Sandbox Code Playgroud)
上面的脚本将在终端中输出以下内容:
$ ['CHECKOUT_REVISION this must be stored', 'CHECKOUT_REVISION another line to store']
Run Code Online (Sandbox Code Playgroud)