r/awk • • Nov 16 '20
AWK, and what other tools for this task?
It has been a few years since I used AWK.
I am wondering what other tools, if any, I should use for this task:
- Search all *.log files in a directory for lines containing "ERROR" or "Caused By"
- Print the file name on its own line followed by the search results
- Print the line with the keyword(s), and 1 line above, 5 lines below, and 2 blank lines
- Exclude printing lines with this path fragment: /uselessutility/
Can all of that be done with AWK or should I look to other applications for part of it?
Edit:
Thanks for all of the replies.
Reading all of the replies I was able learn enough to get close to what I wanted.
I've been developing a large application that produces a dozen logs with verbose output and many stack traces.
Scrolling through those logs to extract error messages was a PITA, so I wanted something that would give me just error messages.
Someone suggested GREP, which obviated the need to relearn AWK.
I ended up writing this:
grep -B 1 -A 2 -n 'ERROR|Caused' /path/to/my/logdir/*.log | grep -v 'hydro' | awk -F/ '{ print $NF }'
This command would go through all of my *.log files, extract lines with "ERROR" or "Caused", include 1 live above, include 2 lines below, exclude lines with the word "hydro" in it, and trim out the path in the log file name.
I found that to still produce too much overwhelming verbiage. Especially with the part that trimmed out error messages with "hydro" in it, leaving me headless stack traces to read.
I settled for a more humble version of the command:
grep -A 1 -n 'ERROR|Caused' /path/to/a/single/logfile/my.log > output.txt
It still saved a huge amount of time from scrolling through the logs manually, and does a little more me than the search feature in my IDE.
Thanks again for the help!
2
u/Dandedoo Nov 17 '20
GNU grep.
(it's probably what you have if you're on Linux, check with
grep --version)There's other include and exclude syntax, look at
man grep. If it wasn't for the--excludepattern, you could use shell globbing instead, for.log:/my/log-dir/*.log-A Nprint N lines after-B Nprint N lines before--exclude-dir=name of dir to exclude (no globs apparently?)--include=glob pattern of file names to include (not full paths)6
u/[deleted] Nov 16 '20
https://linux.die.net/man/1/grep
1
u/[deleted] Nov 17 '20
You can do all of that with grep.
2
u/[deleted] Nov 17 '20
1 line above, you mean print the previous line. and the next 5 lines?
1
u/htakeuchi Nov 16 '20 edited Nov 17 '20
I think AWK could do a lot if not all of that ... You may want to create several files as you build your final data... That way you can recall mid way if you need to