2

I am trying to parse the date-time part from the following -

[Tue Oct  4 11:55:19 2016] [hphp] [25376:7f5d57bff700:279809:000001] [] \nFatal error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting ')' in /var/cake_1.2.0.6311-beta/app/webroot/openx/www/delivery/postGetAd.php(12479)(62110d90541a84df30dd077ee953e47c) : eval()'d code on line 1

With the following command -

/usr/local/nagios/libexec/check_logwarn -d /tmp/logwarn -p /mnt/log/hiphop/error_`(date +'%Y%m%d')`.log "^.*Fatal*" | awk '{print $1" "$2" "$3" "$4" "$5}' 

I get the following output (with the brackets []) -

[Wed Oct 5 09:49:49 2016]

I want to get only the date-time part and then do some comparison. See my other question Parsing lines from a log file containing date-time greater than something

I tried using gsub to replace the brackets, but it gives me the following error -

/usr/local/nagios/libexec/check_logwarn -d /tmp/logwarn -p /mnt/log/hiphop/error_`(date +'%Y%m%d')`.log "^.*Fatal*" | awk '{ gsub("/\[\","T",$1); print $1" "$2" "$3" "$4" "$5}' 

Output -

awk: (FILENAME=- FNR=1) fatal: Invalid regular expression: /[/

It seems I need to escape the [. I tried using \[ but with no success. Output -

awk: warning: escape sequence `\[' treated as plain `['
awk: (FILENAME=- FNR=1) fatal: Invalid regular expression: /[/
Community
  • 1
  • 1
Sandeepan Nath
  • 9,966
  • 17
  • 86
  • 144

2 Answers2

4

If you use the /.../ regex syntax, you can escape with a single backslash:

$ echo '[abc]' | awk '{ gsub(/\[/,"") }1'
abc]

Or you can use string-literal syntax, but then you need an extra backslash, (because when the string gets resolved to a regex, the \\[ becomes the desired \[).

$ echo '[abc]' | awk '{ gsub("\\[","") }1'
abc]

Similarly, to remove both opening and closing brackets:

$ echo '[abc]' | awk '{ gsub(/[\[\]]/,"") }1'
abc

or

$ echo '[abc]' | awk '{ gsub("[\\[\\]]","") }1'
abc
jas
  • 10,715
  • 2
  • 30
  • 41
  • `echo '[ABC]' | awk '{gsub(/[[\]]/,"") } 1'` returns ´ABC´ as well. – James Brown Oct 05 '16 at 11:12
  • 1
    Good point, @JamesBrown. Interestingly, so does `gsub(/[][]/,"")`. – jas Oct 05 '16 at 11:35
  • Using your answer, ` /usr/local/nagios/libexec/check_logwarn -d /tmp/logwarn -p /mnt/log/hiphop/error_20161006.log "^.*Fatal*" | awk 'gsub(/\[/,"",$1); gsub(/\]/,"",$5);' | awk '{print $5}'` gives me the following output - `2016 2016] 2016 2016]`. Not sure, why the `]` remains in alternative lines. Whereas with @VIPIN KUMAR's answer, it works fine. – Sandeepan Nath Oct 07 '16 at 09:42
  • What is the role of the `1` at the end of the code `}1'`? – Sander W. van der Laan Mar 22 '18 at 15:18
  • 1
    @SanderW.vanderLaan, the `1` is shorthand for `{ print $0 }` as explained here: https://stackoverflow.com/questions/20262869/why-does-1-in-awk-print-the-current-line – jas Mar 22 '18 at 22:26
1
echo "[Wed Oct 5 09:49:49 2016]"|tr -d '[]'
VIPIN KUMAR
  • 3,019
  • 1
  • 23
  • 34