zsh-users
 help / color / mirror / code / Atom feed
* Fun zsh trick for today
@ 2000-06-10 22:50 Bart Schaefer
  0 siblings, 0 replies; 12+ messages in thread
From: Bart Schaefer @ 2000-06-10 22:50 UTC (permalink / raw)
  To: zsh-users

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   


^ permalink raw reply	[flat|nested] 12+ messages in thread
[parent not found: <no.id>]

end of thread, other threads:[~2000-06-14 16:32 UTC | newest]

Thread overview: 12+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2000-06-10 22:50 Fun zsh trick for today Bart Schaefer
     [not found] <no.id>
2000-06-14 13:43 ` Matthias Kopfermann
2000-06-14 13:57   ` Clint Adams
2000-06-14 14:09     ` Ollivier Robert
2000-06-14 15:02       ` Fletch
2000-06-14 14:15     ` Peter Stephenson
2000-06-14 14:21       ` Peter Stephenson
2000-06-14 14:27       ` Clint Adams
2000-06-14 14:37       ` Bart Schaefer
2000-06-14 15:33 ` Matthias Kopfermann
2000-06-14 15:52   ` Peter Stephenson
2000-06-14 16:31 ` Matthias Kopfermann

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).