Bash script: using variables / parameter in sed -
i trying write little bash script, can specify number of minutes , show lines of log file last x minutes. lines, using sed
sed -n '/time/,/time/p' logfile on cli works perfectly, in script however, not.
# date now=$(date "+%y-%m-%d %t") # date minus x number of minutes -- $1 first argument, minutes then=$(date -d "-$1 minutes" +"%y-%m-%d %t") # filter logs -- $2 second argument, filename sed -n '/'$then'/,/'$now'/p' $2 i have tried different approaches , none of them seem work:
result=$(sed -n '/"$then"/,/"$now"/p' $2) sed -n "/'$then'/,/'$now'/p" "$2" sed -n "/$then/,/$now/p" $2 sed -n "/$then/,/$now/p" "$2 any sugesstions? on debian 5, echo $shell says /bin/sh
edit : script produces no output, there no error showing up. in logfile every entry starts date 2013-05-15 14:21:42,794
i assume main problem try perform arithmetic comparison string matching. sed -n '/23/,/27/p' gives lines between first line contains 23 , next line contains 27 (and again next line contains 23 next line contains 27, , on). not give lines contain number between 23 , 27. if input looks like
19 22 24 26 27 30 it not output (since there no 23). awk solution uses string matching has same problem. so, unless then date string occurs verbatim in log file, method fail. have convert date strings numbers (drop -, <space>, , :) , check whether resulting number in right range, using arithmetical comparison rather string match. goes beyond capabilities of sed; awk , perl can rather easily. here perl solution:
#!/bin/bash now=$(date "+%y%m%d%h%m%s") then=$(date -d "-$1 minutes" "+%y%m%d%h%m%s") perl -wne ' if (m/^(....)-(..)-(..) (..):(..):(..)/) { $date = "$1$2$3$4$5$6"; if ($date >= '"$then"' && $date <= '"$now"') { print; } }' "$2"
Comments
Post a Comment