So I was told to do last > lastloggedin which creates a file that shows the classes last login since the last system reboot, and now I am asked to write an Awk script which is named myawk that counts/determines how many lines of lastloggedin contain the string CFS264.
I’ve done grep -c CFS264 lastloggedin
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
To get you started you can use awk to search for lines in a file that contain a string like so:
$ awk '/CFS264/ { .... }' lastloggedin
The bits in the { .... } will be the commands required to tally up the number of lines with that string. To confirm that the above is working you could use a print $0 in there to simply print those lines that contain the search string.
$ awk '/CFS264/ { print $0 }' lastloggedin
As to the counting, if you search for “awk counter” you’ll stumble upon this SO Q&A titled: using awk to count no of records. The method shown there would suffice for what you describe:
$ awk '/CFS264/ {count++} END{print count}' lastloggedin
Example
$ last > lastloggedin
$ awk '/slm/ {count++} END {print count}' lastloggedin
758
$ grep slm lastloggedin | wc -l
758
$ grep -c slm lastloggedin
758
NOTE: You don’t say which field CFS264 pertains to in the last output. Assuming it’s a username then you could further restrict the awk command to search only that field like so:
$ awk '$1=="CFS264" { print $0 }' lastloggedin
Method 2
The following example counts the times I am mentioned without needing the lastloggedin file:
$ last | awk '$1=="yeti" { ++count } END { print count }'
106
If you insist in using or are forced to use the lastloggedin file, you can do it this way:
$ last > lastloggedin
$ awk '$1=="yeti" { ++count } END { print count }' lastloggedin
106
Use $1~/some_chars/ to get all user names containig the given chars or $1~/^prefix/ to match only names starting with prefix:
$ last | awk '$1~/et/ { ++count } END { print count }'
106
$ last | awk '$1~/^ye/ { ++count } END { print count }'
106
P.S.:
Scan man awk for more hints… 😉
awk is very rewarding: You can do lots of stuff after a very short time of learning…
Method 3
Last can includes users logins from previous reboots. As such, the following will only print users since the last reboot:
last | awk 'NR==1,$1=="reboot"{if ($1 ~ /cfs264/ ) { count+=1; }}END{ print count; }'
The first part of the awk command specifies a range – start from the first row until the first column is ‘reboot’.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0