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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-10-28 11:00:00 +0000
Seen: 7 times
Last updated: Aug 08 '22
How can popen() be used to direct streaming data to TAR?
In Python, can a string be utilized to retrieve a dataframe that has the same name as the string?
What is the method for merging field value and text into a singular line for display?
What is the method for programmatic access to a time series?