Friday, April 1, 2016
Linux Bash Shell Script Time Interval Regex with Piped Loop to Print Log Data
April 01, 2016
beginner
,
code
,
easy
,
explanation
,
expression evaluation
,
grep while
,
linux
,
pipelining
,
piping
,
read line by line in variable
,
regex
,
regular expression
,
script
,
shell
,
time interval matching
,
time regex
,
tutorial
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".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Code To Match Time Interval:
Save the code in a file named "TimeIntervalRegex.sh".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment