I am trying to find a Linux command which could give me the text between [ and ]. I tried standard grep and sed but none helped for far.Say the text is in LOGS. like -
Starting mongo client..
Connecting to truststore.pki.rds.amazonaws.com (99.84.66.9:443)
global-bundle.pem 100% |********************************| 183k 0:00:00 ETA
MongoDB shell version v4.0.6
connecting to: mongodb://XXXx.amazonaws.com:27017/?authSource=XXX&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("XXXXXXX") }
MongoDB server version: 5.0.0
WARNING: shell and server versions do not match
----------------------------------------------------------------------------------------------------
Listing Existing set of collections
----------------------------------------------------------------------------------------------------
[
"10w",
"11w",
"Test1",
"Test2",
"QA_Testing",
"QueuesTest",
"TestPagination",
]
I wanted the text only this collection names inside []
Tried so far
echo "$LOGS" | grep -o "\[.*\]"
echo "$LOGS" | sed -n 's/.*\[\([^]]*\)\].*/\1/p'
echo "$LOGS" | grep -o '\[\K[^\]]+'
echo "$LOGS" | awk -F'[][]' '{for(i=2;i<=NF;i+=2) print $i}'
None of them helped so far. They are not showing any error but not also any output. Can anyone please help with the correct command which can help me
burcu's answer is perfect. As I prefer using the if
statement in awk
, here is my answer:
awk '{
if ($0 == "[") {
in_bracket = 1
next
}else if ($0 == "]"){
in_bracket = 0
}
if (in_bracket) {
print $0
}
}' a.txt