![](/img/trans.png)
[英]TCL script search string from file1 & file 2 and replace it in file1
[英]Python : Search patterns from file1 in a list of files
我有一個包含所有模式列表的文件。 模式具有這種格式(高:低)。 高和低之間用冒號隔開。
file1中的樣本模式:
-6447867851221037056:-3788579599719006014
-6449238495544274944:-3932696454242172736
-6449265231715692544:-4004752252983770939
-6449203349826891776:-2995947018784538426
-6447968581089030144:-3659104829784325951
-6449244980944891904:-1059398397250633536
-6449247532155465728:-1915082300761767744
-6447984223359922176:-4220924871888797497
現在,我在搜索目錄中有了文件列表。 我想在與文件*
yyyy-mm-dd-hh *
模式匹配的搜索目錄中的所有文件中,從上述文件中搜索模式。
例如:
使用文件名模式從搜索目錄中的file1搜索所有模式*
2015-09-07-06 *
search_file.2015-09-07-05-45
search_file.2015-09-07-06-47
search_file.2015-09-07-06-48
search_file.2015-09-07-06-50
search_file.2015-09-07-06-52
我知道如何在bash中執行此操作(grep -f file1 *
2015-09-07-06 *
)。 但是我是python的新手,對如何進一步進行了解甚少。 任何類型的指針都值得贊賞
高效而簡便的方法是使用shell命令。 希望您知道os.system在python中執行shell命令。 我在python中嘗試了相同的邏輯。
import glob
file_list = glob.glob("*2015-09-07-06*")
input_filename = "file1.txt"
with open(input_filename,'r') as input:
input_data = input.readlines()
for each_file in file_list:
open_file = open(each_file,'r')
file_data = open_file.readlines()
identified = set(input_data) & set(file_data)
if identified:
print "filename : " + str(each_file)+" : "+str(identified)
import re
def searchpattern():
with open("file1.txt", 'r') as fobj:
f = fobj.readlines()
pattern = '2015-09-07-06'
for i in f:
m = re.search(pattern, i)
if m:
print(i)
else:
pass
if __name__ == '__main__':
searchpattern()
輸出:
2015-09-07-06-45
2015-09-07-06-46
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.