Find a string on one line and return the string directly below the found string - Python or UNIX

python one-liner
python one line converter
grep multiple strings output on same line
grep multiple strings and condition
python string find
python split string
python substring in string
python check if string contains substring from list

I am having trouble coming up with a way to parse a file in python. The file has rows with random letters and characters (see below).

ABCDBCADBADCBABDDACAABCDB 
1#JHHHF##@@GGIHHHIII==DDS
ACBDAACBABDCCBBDCDBBADADA
ISHFIDH#H@1JD=@HHII##GG=H
CCCDDAABCCBABBADBADBAAABA
%%$$#@GGTTT&%MHTHWAIIHJWI

Given a string, e.g. 'BAD' return or print the characters immediately below it. For this file, the code should return:

#@@
##G
MHT
HWA

Thanks for any assistance!

Here's what I've started with:

#!/usr/bin/python
f=open('file.txt')
lines=f.readlines()
num_lines = sum(1 for line in open('file.txt'))
x = 0
while x <= num_lines:
    _str = lines[x]
    loc = _str.find('BAD')
    x = x+1
    _str = lines[x]
    print (_str[loc:loc+2]
    x=x+1

You are close to the solution. Step through the pairs of lines, find the marker ("BAD") in the first and the word with the same index in the second:

marker = 'BAD'
marker_len = len(marker)

for l1, l2 in zip(lines, lines[1:]):
   i = l1.find(marker) # Find the first marker
   while i != -1: # Are there any more markers?
     print(l2[i:i + marker_len])
     i = l1.find(marker, i + marker_len) # Search the rest of l1
# #@@
# ##G
# MHT
# HWA

Python, a inbuilt function find() which checks if a substring is present in the string, which is done in one line. find() function returns -1 if it is not found, else it returns first  If the substring is not found, the find method will return -1. Meaning that the substring was not found in the parent string. If the substring is found, the find method will return the starting index of the first character of the substring.

A solution using re module:

import re
str = """ABCDBCADBADCBABDDACAABCDB 
1#JHHHF##@@GGIHHHIII==DDS
ACBDAACBABDCCBBDCDBBADADA
ISHFIDH#H@1JD=@HHII##GG=H
CCCDDAABCCBABBADBADBAAABA
%%$$#@GGTTT&%MHTHWAIIHJWI"""

length = int(len(str)/len(str.split('\n')))
p = re.compile("BAD")
for m in p.finditer(str):
    i = m.start()+length
    j = m.end()+length
    print (str[i:j])

Prints:

##@
##G
MHT
HWA

Powerful Python One-Liners, The ability to write short programs that are just as powerful as a the substring "​at" by "op" on all lines of all files (in place) under the path specified (here, the current path). Caution: Don't run this on your home directory or you're going to get all This can be used to convert a string into a "url safe" string. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more Find a string on one line and return the string directly below the found string - Python or UNIX

Singleline using re:

import re

data = '''
ABCDBCADBADCBABDDACAABCDB
1#JHHHF##@@GGIHHHIII==DDS
ACBDAACBABDCCBBDCDBBADADA
ISHFIDH#H@1JD=@HHII##GG=H
CCCDDAABCCBABBADBADBAAABA
%%$$#@GGTTT&%MHTHWAIIHJWI
'''

print(re.findall(r'(?=(?:BAD))(?=(?:.{%s}(...)))' % (len(max(data.splitlines())) + 1), data, flags=re.DOTALL))

Prints:

['#@@', '##G', 'MHT', 'HWA']

Explanation of this regexp here.

Search Multiple Words / String Pattern Using grep Command on , How do I search multiple strings or words using the grep command? Use single quotes in the pattern: grep 'pattern*' file1 file2; Next use extended Grep searching two words in a line Search all python files for 'wordA' or 'wordB' ### Get the latest tutorials on SysAdmin, Linux/Unix and open source  Now you can see that FIND brought up one line that matches the search string, which means it is working. Let’s try this again, but change the search string to “sushi”; if your results look like the image below, you did it right. Scenario 2 – Search multiple documents for the same string of words.

Replace string in line of file python, Python string method replace () returns a copy of the string in which the There are actually a number of ways to read a text file in Python, not just one. Below are the list of string methods available in Python 3. With sed you can search, find and replace, insert, and delete strings and lines. If not found, it returns -1. You can go from a list to a string in Python with the join () method. The common use case here is when you have an iterable—like a list—made up of strings, and you want to combine those strings into a single string. Like .split (), .join () is a string instance method.

re – Regular Expressions, They are also an integral part of Unix command line utilities such as sed, grep This example looks for two literal strings, 'this' and 'that', in a text string. search() takes the pattern and text to scan, and returns a Match object when the pattern is found. have all used search() to look for single instances of literal text strings. just type it, while script will be written :). ok, you should open some file, find the string and then paste it to the other file like this. [code]stringToMatch

Python Strings | Python Education, A double quoted string literal can contain single quotes without any fuss (e.g. The len(string) function returns the length of a string. Notice in the code below that variables are not pre-declared -- just assign to them and go. A google search for "python str" should lead you to the official python.org string  In this tutorial, you can quickly discover the most efficient methods to convert Python List to String. Several examples are provided to help for clear understanding. Python provides a magical join () method that takes a sequence and converts it to a string. The list can contain any of the following object types: Strings, Characters, Numbers.

Comments
  • str is a built-in datatype. Do not overwrite it.
  • Thanks! This works great! The l1, l2, and zip are completely new to me!
  • l1 and l2 are just variable names.
  • FWIW, You don't need to read all the lines. In fact, unless you can guarantee the input is small you shouldn't read all the lines up front. It is sufficient, and far more efficient, to do for l1, l2 in zip(f, f):.
  • Good to know. I'll adjust the script. Thanks!
  • What is the meaning of 26?
  • Yeah cheers, calculated the offset in the terminal but forgot to include it in the snippet. Edited the answer.