I am using Python3 to try to emulate
awk '/STRING/'
I made some code that works, but it stops on the first instance instead of finding all lines that contain the specified character/string.
After I made the code, I saw these two pages, but the suggestions did not work
Print line containing "word" python
Search and get a line in Python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Made by Devyn Collier Johnson, NCLA, Linux+, LPIC-1, DCTS
def cat(openfile): #Emulates cat#
with open(openfile) as file:
lines = file.readlines()
return ''.join(lines)
def GETLINEWITH(FILECONTENTS, CONTAINING):
for item in FILECONTENTS.split('\n'):
if CONTAINING in item:
return item.strip()
print(GETLINEWITH(cat('./Base.xaiml'), 'terminal'))
I have a file (./Base.xaiml) that contains several instances of the word "terminal". I am using this file and string for testing purposes.
EDIT: I also want to save the results to a variable -
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Made by Devyn Collier Johnson, NCLA, Linux+, LPIC-1, DCTS
def cat(openfile): #Emulates cat#
with open(openfile) as file:
lines = file.readlines()
return ''.join(lines)
def GETLINEWITH(FILECONTENTS, CONTAINING):
for item in FILECONTENTS.split('\n'):
if CONTAINING in item:
print(item.strip()) #I implemented the give suggestion
VAR = GETLINEWITH(cat('./Base.xaiml'), 'terminal'))
Results:
I tried Jon Clements suggestion:
with open('./Base.xaiml') as fin:
matching = ('terminal' in line for line in fin)
for line in matching:
VAR = matching
print(VAR)
However, the output is one memory address. ''.join() and group() do not help.
Edit2:
Newest code Issues - nonetype error and the output cannot be saved to a variable
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Made by Devyn Collier Johnson, NCLA, Linux+, LPIC-1, DCTS
def cat(openfile): #Emulates cat#
with open(openfile) as file:
lines = file.readlines()
return ''.join(lines)
def GETLINEWITH(FILECONTENTS, CONTAINING):
for item in FILECONTENTS.split('\n'):
if CONTAINING in item:
print(item.strip())
for line in GETLINEWITH(cat('./Base.xaiml'), 'terminal'):
print(line)