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

Re: Parameter expansion: tr?



On Apr 6,  3:13pm, Vincent Lefevre wrote:
} Subject: Parameter expansion: tr?
}
} I've seen how one can do a string substitution in a parameter expansion,
} but how can I do a tr, e.g. to swap the "." and "/" characters?
} 
} Is there a simple way to do that, or do I need associative arrays?

The following requires 3.1.9 or later:

  function ztr {
    setopt extendedglob noshwordsplit
    local chunk=''
    while read -u0k 4096 chunk; do
	print -Rn ${chunk//(#b)([$1])/${2[${1[(I)$match]}]}}
	chunk=''
    done
    # "read -k" will exit nonzero on the last partial chunk, print it
    (( $#chunk )) && print -Rn ${chunk//(#b)([$1])/${2[${1[(I)$match]}]}}
  }

% ztr "abcde ." "NOPQR-/" <<EOF
The quick brown fox jumped over the lazy dog.
EOF
ThR-quiPk-Orown-fox-jumpRQ-ovRr-thR-lNzy-Qog/
% 

I think the "read -k" behavior on a partial chunk is a bug, but I seem to
recall some zsh-workers discussion to the effect that other shells also
behave that way.  I may be thinking of some other "read" behavior, though.

Using ${1[(I)$match]} emulates the real `tr aaa xyz` == `tr a z` behavior.
If you give the above function only one argument, it acts like "tr -d".
"tr -s" and "tr -c" left as exercises for the reader.

-- 
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