Friday, 12 April 2013

Unix Ulitity to grep a search string with few lines before and after the match

OEL Linux has an option in  grep command to search a string with some lines before and after the  match.
This utility helps us to search an ERROR  from the alert.log/trace with timestamp which is recorded one line before the actual error.
Unfortunately this option is not available in some of the platform like the Solaris and AIX ( of course  there are addition packages to have enhanced grep option)
The following small wrapper script to simulate the same grep option available in Linux







Script:
# usage <grep_add.sh> <no_rows_b4> <no_rows_a4> <search_string> <file_name>
b4=$1
a4=$2
search_string=$3
file_name=$4
grep -n $search_string $file_name | cut -d':' -f1 |  xargs  -n1 -I % awk "NR<=%+$a4 && NR>=%-$b4" $file_name




==========================================================
Usage:
grep_add.sh 1 0 force_match coe_xfr_sql_profile_56c1s0454r13x_1115266317.sql
replace     => TRUE,
force_match => FALSE /* TRUE:FORCE (match even when different literals in SQL). FALSE:EXACT (similar to CURSOR_SHARING) */ );
grep_add.sh  2 2 force_match coe_xfr_sql_profile_56c1s0454r13x_1115266317.sql
validate    => TRUE,
replace     => TRUE,
force_match => FALSE /* TRUE:FORCE (match even when different literals in SQL). FALSE:EXACT (similar to CURSOR_SHARING) */ );
DBMS_LOB.FREETEMPORARY(sql_txt);
END;
=======================================================











Linux Option:
In linux ,this option comes with the exisitng grep command , we can use -B and -A option to grep the additional lines
grep -A 3 FIXED awrinfo.txt
FIXED      39,506.7   44.2        3,272      306.7     2,147.2    47% : 53%
EVENTS     32,080.4   35.9        2,657      249.1     1,743.6    39% : 61%
ASH        11,324.3   12.7          938       87.9       615.5    89% : 11%
SPACE       3,275.4    3.7          271       25.4       178.0    68% : 32%
$ grep -B 2 FIXED awrinfo.txt
COMPONENT        MB  % AWR  KB_PER_SNAP MB_PER_DAY MB_PER_WEEK TABLE% : INDEX%
--------- --------- ------ ------------ ---------- ----------- ----------------
FIXED      39,506.7   44.2        3,272      306.7     2,147.2    47% : 53%

No comments:

Post a Comment

ZFS

Public Cloud tools comparison