I'm trying to write a script to pull logs between two timestamps using awk.
So this works :
awk '$0 >= "07-Nov-2021 13:40:02.124" && $0 <= "07-Nov-2021 13:43:08.124"' websniffer.log
But when I use it within a bash script, I'm struggling to get it work. Here's my minimal sample script & error :
#!/bin/bash
fromtime=$1
totime=$2
nameoffile="websniffer.log"
awk -v fromtimestamp=$fromtime -v totimestamp=$totime -v filenm=$nameoffile '$0 >= "$fromtimestamp" && $0 <= "$totimestamp"}' $filenm
Now when I execute this script by :
#terminal@root$ ./samplescript.sh "07-Nov-2021 13:40:02.124" "07-Nov-2021 13:43:08.124"
I get this :
./samplescript.sh "07-Nov-2021 13:40:02.124" "07-Nov-2021 13:43:08.124"./samplescript.sh "07-Nov-2021 13:40:02.124" "07-Nov-2021 13:43:08.124" ./samplescript.sh: line 6: 2190 Segmentation fault awk -v fromtimestamp=$fromtime -v totimestamp=$totime -v filenm=$nameoffile '$0 >= "$fromtimestamp" && $0 <= "$totimestamp"}' $filenm
Can someone please help in getting this working ?
There's a couple of things:
#!/bin/bash
fromtime=$1
totime=$2
nameoffile="websniffer.log"
awk -v fromtimestamp="$fromtime" -v totimestamp="$totime" '$0 >= fromtimestamp && $0 <= totimestamp' "$nameoffile"
You need to quote the shell variables you pass to awk (they have whitespace in them) and there's no need to create filenm and pass it to awk since you're not using it within the awk script.