Monday, September 10, 2007

zsh magic




mmm, zsh is the most awesome shell in the world. I had a slightly tricky problem where I wanted to get the last occurrence of a line that matched a pattern in a logfile, and wanted to do this over multiple logfiles.

I was going to use find, and just about had a command line that would do this, but then I realized that I'm living in zsh, and maybe...

so, I went to the zshtips page, and found what I was looking for. here's what I came up with:


new 283 [~/bittorrent] % for i in **/*.txt; grep -H percent $i | tail -1
mckenna-lecture-1.txt:percent done: 100.0
mckenna-lecture-2.txt:percent done: 100.0
mckenna-lecture-3.txt:percent done: 31.6
mckenna-lecture-4.txt:percent done: 25.0
mckenna-lecture-5.txt:percent done: 100.0
mckenna-lecture-6.txt:percent done: 1.0
mckenna-lecture-7.txt:percent done: 23.0


What this does is:
- look in all files that end it *.txt
- find any lines that match "percent"
- take the last line of this match
- print out the filename of those matching files as well

This is probably more readable than the corresponding find command.