How can I find a string in a text file if I know only the part of the string? For example, I know only ".someserver.com"
But the whole text in the file looks like the following:
"hostname1.expedite.someserver.com"
So the point is to find the whole name by knowing only a part of it.
part of the file content:
{"attributes": {"meta_data": {"created_at":1614882362.179626, "created_by": "admin"}, "site": "AF002"}, hostname:"hostname1.expedite.someserver.com",
Assuming your data looks like:
{"attributes": "xyz", "hostname": ":hostname1.expedite.someserver.com"}
{"attributes": "xyz", "hostname": ":hostname1.expedite.another.com"}
{"attributes": "xyz", "hostname": ":hostname1.expedite.server.com"}
{"attributes": "xyz", "hostname": ":hostname1.expedite.we.com"}
{"attributes": "xyz", "hostname": ":hostname1.expedite.dont.com"}
{"attributes": "xyz", "hostname": ":hostname1.expedite.care.com"}
We can:
import ast
check = ".someserver.com"
with open("string.txt", "r") as f:
line = f.readline()
while line:
if check in line:
print(dict(ast.literal_eval(line))["hostname"])
line = f.readline()
this prints us:
:hostname1.expedite.someserver.com
Assuming the data looks like:
[{"attributes": "xyz", "hostname": ":hostname1.expedite.someserver.com"}, {"attributes": "xyz", "hostname": ":hostname1.expedite.another.com"}, {"attributes": "xyz", "hostname": ":hostname1.expedite.server.com"}, {"attributes": "xyz", "hostname": ":hostname1.expedite.we.com"}, {"attributes": "xyz", "hostname": ":hostname1.expedite.dont.com"}, {"attributes": "xyz", "hostname": ":hostname1.expedite.care.com"}]
We then can:
import json
check = ".someserver.com"
data = json.load(open("string2.txt", "r"))
for d in data:
if check in d["hostname"]:
print(d["hostname"])
This gives us:
:hostname1.expedite.someserver.com