For example, the first match “ RuntimeException…” is located at line 2 6 – 1 = 7 in the app.log file. Of course, we can get the actual line numbers through this calculation: LINE_NO_BY_GREP 6 – 1. However, since we piped the tail command’s output to grep, the line numbers reported by the grep command are not the actual line numbers in the original input file. So, let’s execute the command with the -n option: $ tail -n 6 app.log | grep -n 'Exception'Ģ: RuntimeException: File not found: /foo/bar/newFileĤ: TemplateNotFoundException: Template PRETTY not found, loading the default templateĦ: Cleanup job done with IOException: Disk is fullĪs we can see, this time, the command has printed the line numbers of matched lines. For example, this helps us locate the log entries with “ Exception” and take a closer look at the stack trace to analyze the cause. Of course, using -n turns on line numbering, so the -A and -B options are better if you don't want line numbers. However, sometimes, we would like to execute the grep command with the -n option to print the line numbers of each match. As well as the options mentioned by Steven D, GNU grep accepts an (undocumented) arg to the -n option that specifies the number of lines to print before and after a matched line. RuntimeException: File not found: /foo/bar/newFileĪs we can see, the command above has solved the problem. grep -C 3 foo README.txt This will show 3 lines before and 3 lines after. grep -B 3 -A 2 foo README.txt If you want the same number of lines before and after you can use -C num. Next, let’s execute the grep command on the output above to get the required log entries: $ tail -n 6 app.log | grep 'Exception' For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. The first idea to solve the problem is to extract the lines that we want to look at first, then execute grep on those lines. Cleanup job done with IOException: Disk is full TemplateNotFoundException: Template PRETTY not found, loading the default template
0 Comments
Leave a Reply. |