Grep is my enemy...

Geraint Edwards gedge-lists at yadn.org
Thu Oct 5 08:32:23 BST 2006


Michael Abbott <michael at araneidae.co.uk> said
		(on Wed, Oct 04, 2006 at 04:51:05AM +0000):
> It's rather a shame that [echo] fails if (and only if) $STRING 
> matches '^-[neE]+$': if anyone knows a more reliable method, please do 
> say!

Well, you might be tempted to fudge a workaround like this:

	echo x"$STRING" | sed 's/^x//' |
	grep -f <(grep -v '^[[:space]]*$' "$PATTERN_FILE")

but(!) that doesn't work if $STRING is multi-line (e.g. consider
STRING="FOO\nxBAR"), so you may need to move up to awk(1):

	echo x"$STRING" | awk '{if(NR==1){sub(/^x/,"")}print}'

For the awk-shy:  the block (with the outer {}s) has no preceding
condition, so awk will execute that block for all lines.  NR is
the number of the current record (aka line number).

The below is equivalent, but has two blocks, the first of which
is conditionally applied:

	echo x"$STRING" | awk 'NR==1{sub(/^x/,"")}{print}'

Hope this helps.

-- 
Geraint A. Edwards (aka "Gedge")
gedge at yadn.org




More information about the Ukfreebsd mailing list