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

Re: optimal expansions?



On Sat, Apr 20, 2024, at 10:23 AM, Ray Andrews wrote:
> ... this line is Basque to me.  It works but I have no idea how.  
> Anyway that's for me to research.  It baffles me that there's color 
> codes in there.
>>           print -P "%B%2F${pkg//\%/%%}%f%b"
>>         fi

The "-P" option tells "print" to interpret prompt escapes like "%B"
and "%F" (see zshmisc(1)), allowing you to avoid hardcoding ECMA-48
escape sequences.  The "${pkg//\%/%%}" expansion interpolates the
package name with all "%" characters escaped.


> Seems we want '-r' most of the time.

Yes, unless you actually do want "print" to interpret substrings
like "\n".  Sometimes you do, sometimes you don't.  If the operands
are dynamic and not under your control, you generally don't.


> Now that I know not to use newlines for splitting.  And of 
> course that obviates most of my '(@f)'s too.

That's because Roman's solution uses "read" to stream the output
from "apt-file" instead of saving it all and postprocessing it.
This doesn't have anything to do with "print" though.


> But I'm betting your code will be faster.

If speed is a concern...

% cat af_awk
#!/bin/sh -

apt-file search -- "$1" | awk '
	BEGIN {
		fg_bld_grn = "\33[1;32m"
		reset = "\33[0m"
	}

	$1 != last_pkg {
		last_pkg = $1
		printf "\n%s%s%s\n", fg_bld_grn, $1, reset
	}

	{
		# Preserve runs of blanks in paths.
		print substr($0, 1 + index($0, " "))
	}

	END {
		# Lack of input implies that apt-file failed.
		exit !NR
	}
'
% apt-file search .txt | wc -l
138962
% for x in ray roman awk; do eval time ./af_$x .txt; done >/dev/null
./af_ray .txt  39.43s user 1.74s system 102% cpu 40.099 total
./af_roman .txt  12.99s user 24.97s system 130% cpu 29.069 total
./af_awk .txt  3.08s user 1.02s system 131% cpu 3.131 total


-- 
vq




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