Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Fun zsh trick for today



Some of you are probably familiar with Perl's "grep" function; given a
regular expression and an array, it returns all the elements of the array
that match the expression.  A common Perl idiom is

	open(FILE, "<somefile");
	@result = grep(/pat/, <FILE>);

Where <FILE> slurps somefile into memory as an array of lines.

Did you know that zsh can do that, too?

If you load the mapfile module:

	zmodload -i zsh/mapfile

Then you can write Perl's open(FILE, "<somefile") as

	$mapfile[somefile]

And you can write <FILE> as

	${(f)mapfile[somefile]}

with the caveat that blank lines are stripped out.

(If you're using zsh 3.0.x or can't load the mapfile module, you can do the
same thing with "${(f)$(<somefile)}".  It's just not quite as efficient,
and you have to remember to use the double quotes around it.)

You can write grep(/pat/, array) as

	${(M)array:#*pat*}

with the caveat that pat is a glob pattern -- but with extendedglob set,
zsh's glob patterns are full regular expressions, although with a non-sed-
like syntax because of the different special meaning of '*'.

So finally, @result = grep(/pat/, <FILE>) is

	result=(${(M)${(f)mapfile[somefile]}:#*pat*})

Try, for example, ${(M)#${(f)mapfile[ChangeLog]}:#*Sven*} to see that there
are 1023 mentions of Sven's name in zsh's ChangeLog file.  (I only managed
265 "Bart"s; in fact, there are only 475 lines with the word "zsh"!)

-- 
Bart Schaefer                                 Brass Lantern Enterprises
http://www.well.com/user/barts              http://www.brasslantern.com

Zsh: http://www.zsh.org | PHPerl Project: http://phperl.sourceforge.net   



Messages sorted by: Reverse Date, Date, Thread, Author