13.07.2015 Views

Linux System Administration Recipes A Problem-Solution Approach

Linux System Administration Recipes A Problem-Solution Approach

Linux System Administration Recipes A Problem-Solution Approach

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 9 ■ WORKING WITH TEXT IN FILES-F: sets the field delimiter as : (by default it’s whitespace between nonwhitespace characters).You can also use NF, which is a built-in variable that means the number of fields in the line. $NF givesthe value of the last field in the record.To find out what shells are in use in your system and how many users use each, use this:cat /etc/passwd | awk -F: '{print $NF}' | sort | uniq -c | sort -rnAgain, you set the field delimiter to : and then print the last field in each record. These are sortedinto order, and then uniq -c counts each unique value. Finally, the output from uniq (which will be ashell name and a count for that shell) is sorted into reverse numerical order. That is, the most popularshell is shown first.If you want to kill all of a particular user’s processes at once, you can pipe ps output into awk and usethat output to tell kill what to do:# ps axu | grep jkemp | kill -9 `awk {print $2}`This will kill -9 any process belonging to jkemp. This is pretty extreme, so you’d want to be certainthat jkemp isn’t going to lose any data or that they shouldn’t be doing whatever they’re doing!■ Note pkill -9 -u jkemp would also do this, but awk is obviously more flexible than pkill, which is a singleusetool.You can use awk to determine the total size of the JPG files in a particular directory, perhaps to seewhether it’s worth splitting the JPG files off into a separate directory housed on another disk.ls -l *.jpg | awk '{s+=$5} END {print "Total size: " s}'This takes the fifth field (which is the size of the file) from each line, sums it, and prints the total.■ Note If you have ls aliased to ls -h (to use human-readable sizes rather than block sizes), you’ll need tounalias it with unalias ls before using this command line.To get a rough idea of the popularity of various pages of your website, you can use this one-liner:$ cat /var/log/apache2/access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head -20The access log is space-delimited, and field 7 (in a GET or POST request) will be the page demanded.This data is then piped through sort, the number of occurrences of each unique value (each page) isprovided with uniq -c, and this is reverse-order (that is, highest first) sorted. -head 20 means that youdisplay only the first 20 lines to avoid the very long tail of the files accessed a couple of times. Youroutput will look a bit like this:192Download at WoweBook.Com

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!