Friday, April 1, 2016

Linux Bash Shell Script Time Interval Regex with Piped Loop to Print Log Data


How the code below works:

The code below by getting all the lines within the log.txt with matching times. Next it reads the data line by line in three separate variables and prints the data.

Input File:

Save the input in file named "log.txt".
192.1.4.09 10:30 Arsenal
110.13.5.67 5:12 Chelsea
192.1.45.67 23:21 Man United
199.13.8.23 8:33 Man city
172.11.22.2 18:45 Arsenal
133.13.8.23 10:00 Moon colony
112.11.22.2 8:00 Mars colony
103.13.8.23 9:00 Jupiter colony
12.11.22.2 8:59 Europa colony
view raw log.txt hosted with ❤ by GitHub

Code To Match Time Interval:

Save the code in a file named "TimeIntervalRegex.sh".
#!/bin/bash
c=0
grep -E -w "8:[0-5][0-9]|9:[0-5][0-9]|10:00?" log.txt | while read ip time city ; do
echo "Logged in at $time with ip $ip and city $city "
c=$(( $c + 1 ))
echo "Found so far: $c"
done

Running the Code:

Just type the code below in terminal. Make sure to cd into that directory if you have not opened the terminal in that directory.

bash TimeIntervalRegex.sh

No comments: