Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!


Click here to return to the 'File count' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
File count
Authored by: babbage on May 09, '01 02:33:11PM
Clever. If you wanna wedge your current directory in there, an easy way would be via the backticks trick: "find `pwd` -print | wc -l".

The Unix shell is built around using a series of utilities that each do one small task, and do it very well. By plugging these together in pipes, as you've shown here, you use these commands as filters which, well, filter out the data stream that you send to them. Once you get used to it, you'll probably find yourself using these little tricks all the time.

As an example, one that I use all the time is to generate a list with "grep", rearrange it with the "sort" command, then use "uniq -c" to count & collapse repeated lines, and one more "sort" or "sort -r" (reverse) to again rearrange the list, this time by frequency. Thus:

cd /private/var/log/httpd
grep "does not exist" error_log | sed 's#^.*exist: ##' | sort | uniq -c | sort | more

A line like that will parse over your Apache error log, find all "404 not found" hits, filter out the beginning of the line (assuming that we're not interested in dates here -- just the names of the missing files), then arranges the list into a useful order. I'd paste in a sample here if my logs were doing anything, but they're not (yet).

Another cool trick is conditional or short-circuit execution. Here, you use the command line's "and" (&&) and "or" (||) operators to control command execution. Say for example you want to pat yourself on the back if you're having no 404 errors on your logs, and either way, mail a listing of the results you find. You could do it something like this:

cd /private/var/log/httpd
grep "does not exist" error_log | mail [address]|| echo "no errors!"
grep "does not exist" error_log | mail [address] && echo "some errors!"

Etc. These are kind of weak examples, but I hope they get the point across. You can check on the status of something, and depending on whether that status is "true" or "false", can conditionally take further action, all within one command.

Another related trick, and the one mentioned up above, is to nest one command within another by use of the backtick trick. Here, you have one command -- say, one that formats the date for you, or gets a list of files matching a pattern, or whatever -- and then hand off the results of that command to another wrapper command. For example:

vi ~/`date '+%Y.%m.%d'`.diary   # current yyyy.mm.dd date as file name
vi `grep -ils chris *`          # edit all files that mention my name
Etc.

[ Reply to This | # ]