home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / alt / lang / awk / 11 < prev    next >
Encoding:
Text File  |  1993-01-21  |  2.2 KB  |  83 lines

  1. Newsgroups: alt.lang.awk
  2. Path: sparky!uunet!cs.utexas.edu!news.uta.edu!hermes.chpc.utexas.edu!rshouman
  3. From: rshouman@chpc.utexas.edu (Radey Shouman)
  4. Subject: Re: tolower() function?
  5. Message-ID: <1993Jan22.012739.26965@chpc.utexas.edu>
  6. Organization: The University of Texas System - CHPC
  7. References: <1993Jan19.152725.3510@trentu.ca> <EMCOOP.93Jan19111755@bcars148.bnr.ca> <C184vr.p5q@austin.ibm.com>
  8. Date: Fri, 22 Jan 93 01:27:39 GMT
  9. Lines: 72
  10.  
  11. In article <C184vr.p5q@austin.ibm.com> tbates@austin.ibm.com (Tom Bates)
  12. writes:
  13.  
  14. >Quoting "The AWK Programming Language",
  15. >
  16. >    "The cleanest way to do case conversion in awk is with an array that
  17. >maps each letter...it's better to use...tr"
  18. >
  19. >I often use tr for this very reason. For example:
  20. >
  21. >    echo "HeLlO, wOrLd!" | tr [:upper:] [:lower]
  22. >
  23. >This gives you:
  24. >
  25. >    hello, world!
  26. >
  27. >To use tr from awk:
  28. >
  29. >#!/bin/awk -f
  30. >   {
  31. >   "echo "$0" | tr [:upper:] [:lower:]" | getline
  32. >   print
  33. >}
  34.  
  35. Note that this will give squirelly results if handed any characters
  36. special to /bin/sh, like quotes, or <>|, or backslash, or backtick,
  37. or $, or ...
  38.  
  39. In order to do this generally, one would have to quote the argument to
  40. echo in single quotes, e.g.:
  41.  
  42.   gsub(/'/, "'\\''" $0);
  43.   "echo '"$0"' | tr [A-Z] [a-z]" | getline
  44.  
  45. Doing this inside a shell script would make it look particularly ugly.
  46.  
  47. This approach, while undeniably clever, has a few other drawbacks:
  48.  
  49. 1) It's really slow, if it has to be done repeatedly, since we fork a
  50.    new subshell for each string we want to downcase.
  51.  
  52. 2) It's very Un*x specific.
  53.  
  54.  
  55. tolower and toupper are such innocuously handy functions that I have 
  56. trouble understanding why they weren't included in the original nawk.
  57.  
  58. Here, just for fun, is an alternative implementation of tolower, in awk.
  59. It's probably slower than one based on a mapping array, but it was faster
  60. for me to type:
  61.  
  62. BEGIN {
  63.   Aa = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
  64. }
  65.  
  66. function tolower(str,     s, i, c) {
  67.   i = 1;
  68.   s = str;
  69.   while (match(substr(s, i), /[A-Z]/))
  70.     {
  71.       i += RSTART - 1;
  72.       c = substr(s, i, 1);
  73.       c = substr(Aa, index(Aa,c) + 1, 1);
  74.       s = substr(s, 1, i - 1) c substr(s, i + 1);
  75.       i++;
  76.     }
  77.   return s;
  78. }
  79.  
  80. --Radey
  81. -- 
  82. Radey Shouman                    rshouman@chpc.utexas.edu
  83.