Is there a way to filter text files using grep (or any other tool) so that you can get the parts of the file that are enclosed in curly braces or square brackets?
I have several files that look like this :
universe = {
["stars"] = {
["Sun"] = {
["planets"] = "9",
["life"] = "Yes",
["asteroid"] = "9001"
},
["Alpha Centauri"] = {
["planets"] = "3",
["life"] = "No",
["asteroid"] = "20"
},
["Rigel"] = {
["planets"] = "5",
["life"] = "No",
["asteroid"] = "11"
}
}
}
For example, my intention is to find every block where [“life”] equals “No”. I realized if it could be handled better in a database (or something with structure), but I’m not sure how to convert that data into that.
I
have a bunch of files in this format and I want to run a command to show the part where the condition is true (up to the direct parent parenthesis), so for the previous example I’d love to get:
["Alpha Centauri"] = {
["planets"] = "3",
["life"] = "No",
["asteroid"] = "20"
},
["Rigel"] = {
["planets"] = "5",
["life"] = "No",
["asteroid"] = "11"
}
Can this be done with GREP? Or is there another tool that can do something like this?
Any help is greatly appreciated. Thanks in advance.
Edit
Example 2: https://regex101.com/r/jO9dU5/1
Solution
Try this Lua program:
local function find(w,t,p)
for k,v in pairs(t) do
if v==w then
print(p..".".. k)
elseif type(v)=="table" then
find(w,v,p..".".. k)
end
end
end
find("No",universe,"universe")
Add the definition of universe
before this code.
If you really want to do text processing, try this :
S=[[
universe = {
...
}
]]
for w in S:gmatch('%b[] = {[^{]-"No".-},?') do
print(w)
end