1 | initial version |
To accomplish this in Python, you can use the following steps:
Here's an example code snippet that implements these steps:
import os
import re
dir_path = 'path/to/directory' # define directory path
search_strings = ['string1', 'string2', 'string3'] # define list of strings to search for
output_dir = 'path/to/output/directory' # define output directory path
def search_strings_in_file(filename):
with open(filename, 'r') as f:
lines = f.readlines()
for index, line in enumerate(lines):
for i in range(len(search_strings)):
if re.search(search_strings[i], line):
output_file = os.path.join(output_dir, search_strings[i] + '_' + os.path.basename(filename))
with open(output_file, 'w') as out:
out.writelines(lines[index:index+51])
break
# loop through all files in directory and search for strings
for filename in os.listdir(dir_path):
if filename.endswith('.txt'):
fullpath = os.path.join(dir_path, filename)
search_strings_in_file(fullpath)
This code will search for all occurrences of the strings in each text file in the directory, and if a string is found, it will save the next 50 lines (including the matched line) to a separate file in the output directory. The output file names will include the matching string and the original file name.