Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

For example I have a log file having this entry:

[Wed Aug 08 11:39:41 2012] [error] [client] ModSecurity: [file "/etc/httpd/modsecurity.d/rules/base_rules/modsecurity_crs_20_protocol_violations.conf"] [line "271"] [id "960020"] [rev "2.2.5"] [msg "Pragma Header requires Cache-Control Header for HTTP/1.1 requests."] [severity "NOTICE"] [tag "RULE_MATURITY/5"] [tag "RULE_ACCURACY/7"] [tag ""] [tag "PROTOCOL_VIOLATION/INVALID_HREQ"] [tag ""] Warning. String match "HTTP/1.1" at REQUEST_PROTOCOL. [hostname ""] [uri "/horde/themes/graphics/tree/plusonly.png"] [unique_id "UCJB7VveCGYAAG@BHJgAAAAQ"]

I want to extract all the string pairs starting with character [ and ending in ]. I can use cut or awk to extract using single delimiter, but I need to extract string between starting [ and ending ]. how to accomplish it?

For example, I need to extract:

"[tag "RULE_ACCURACY/7"]"


"[severity "NOTICE"]"

from the log.

I found a solution that first I have to explode the log by add new line after every ] and then using grep to search for required string. Is there any better way to do it?

share|improve this question
up vote 10 down vote accepted

I think this will split the line as you want

sed -e 's/\]/\]\n/g' log | sed -e 's/^ *//g' | awk '/^\[/ {print}'

First put a newline after each ] then remove any leading spaces and finally print the lines beginning with [.

Your input line becomes

[Wed Aug 08 11:39:41 2012]
[line "271"]
[id "960020"]
[rev "2.2.5"]
[msg "Pragma Header requires Cache-Control Header for HTTP/1.1 requests."]
[severity "NOTICE"]
[tag ""]
[tag ""]
[uri "/horde/themes/graphics/tree/plusonly.png"]
[unique_id "UCJB7VveCGYAAG@BHJgAAAAQ"]
share|improve this answer

This one command will do what you want:

grep -o '\[[^]]*\]' inputfile
share|improve this answer
+1, far cleaner. – Jeff Ferland Aug 8 '12 at 17:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.