Emulating "tr" 
Author Message
 Emulating "tr"

Is there an elegant way of emulating the UNIX command "tr"?

I need a function that can be called as tr(s, r1, r2) where r1 and r2 are
strings of equal length, and replaces each occurrence of a character from
r1 in s, with the corresponding character from r2.

All I could manage was using "gsub", as in this example which does the
equivalent of "tr A-Z a-z":

        if(match(s, "[A-Z]")) {
                for(i=1; i<=26; i++)
                        gsub(substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", i, 1), \
                        substr("abcdefghijklmnopqrstuvwxyz", i, 1), s)
        }

But this only works if no characters of r2 appear in r1.

Anyone has a better idea?

TIA,
--
        Amos Shapir
Paper: nSOF Parallel Software, Ltd.
       Givat-Hashlosha 48800, Israel
Tel: +972 3 9388551   Fax: +972 3 9388552        GEO: 34 55 15 E / 32 05 52 N



Thu, 01 Jun 2000 03:00:00 GMT  
 Emulating "tr"

Quote:

> Is there an elegant way of emulating the UNIX command "tr"?  I need
> a function that can be called as tr(s, r1, r2) where r1 and r2 are
> strings of equal length, and replaces each occurrence of a character
> from r1 in s, with the corresponding character from r2.

Don't know whether it's elegant, and it definitely ain't efficient,
but anyway, here it is:

#
function plainchsub(field , old , new , startf , newf , x) {
 newf = "";
 for (x=1 ; x <= length(old) ; x++)
    {arr[substr(old , x , 1)]=substr(new , x , 1)};
 for (x=1 ; x <= length(field) ; x++)
    {if (substr(field , x , 1) in arr)
       {newf = (newf arr[substr(field , x , 1)])}
     else
       {newf = (newf substr(field , x , 1))}};
 return newf}
#

Here's an example of using this function in an AWK program:

#
{print plainchsub($0 , "abc" , "xyz")}
#

--%!PS-Adobe
10 10 scale/M{rmoveto}def/R{rlineto}def 12 45 moveto 0 5 R 4 -1 M 5.5 0 R
currentpoint 3 sub 3 90 0 arcn 0 -6 R 7.54 10.28 M 2.7067 -9.28 R -5.6333
2 setlinewidth 0 R 9.8867 8 M 7 0 R 0 -9 R -6 4 M 0 -4 R stroke showpage
       % Henry Churchyard      http://uts.cc.utexas.edu/~churchh/



Thu, 01 Jun 2000 03:00:00 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Unix like "tr" in TCL

2. string.join(["Tk 4.2p2", "Python 1.4", "Win32", "free"], "for")

3. BEGIN{want[]={"s1o", "s2o", "s2q", "s3q"}

4. Parsing ""D""?

5. "Fifth", "Forth", zai nar?

6. Ruby "finalize", "__del__"

7. beginners "let"/"random" question

8. ANNOUNCE: new "plus"- and "dash"-patches available for Tcl7.5a2/Tk4.1a2

9. Looking for "stdin", "stdout"

10. Hi, this code: text0 = "One $BLAH Three" text1 = "One @BLAH Three" text0.sub!("$BLAH", "Two") text1.sub!("@BLAH", "Two") print text0,"\n" print text1,"\n" produces thiHi, this code: text0 = "One $BLAH Three" text1 = "One @BLAH Three" text0.sub!("$BLAH", "T

11. Match "ab" in "abc", but not in "abd"

12. replace string AFTER "size","initial", "next"

 

 
Powered by phpBB® Forum Software