| 1 |
# translate.awk --- do tr-like stuff |
| 2 |
# |
| 3 |
# Arnold Robbins, [email protected], Public Domain |
| 4 |
# August 1989 |
| 5 |
# February 2009 - bug fix |
| 6 |
|
| 7 |
# Bugs: does not handle things like tr A-Z a-z; it has |
| 8 |
# to be spelled out. However, if `to' is shorter than `from', |
| 9 |
# the last character in `to' is used for the rest of `from'. |
| 10 |
|
| 11 |
function stranslate(from, to, target, lf, lt, ltarget, t_ar, i, c, |
| 12 |
result) |
| 13 |
{ |
| 14 |
lf = length(from) |
| 15 |
lt = length(to) |
| 16 |
ltarget = length(target) |
| 17 |
for (i = 1; i <= lt; i++) |
| 18 |
t_ar[substr(from, i, 1)] = substr(to, i, 1) |
| 19 |
if (lt < lf) |
| 20 |
for (; i <= lf; i++) |
| 21 |
t_ar[substr(from, i, 1)] = substr(to, lt, 1) |
| 22 |
for (i = 1; i <= ltarget; i++) { |
| 23 |
c = substr(target, i, 1) |
| 24 |
if (c in t_ar) |
| 25 |
c = t_ar[c] |
| 26 |
result = result c |
| 27 |
} |
| 28 |
return result |
| 29 |
} |
| 30 |
|
| 31 |
function translate(from, to) |
| 32 |
{ |
| 33 |
return $0 = stranslate(from, to, $0) |
| 34 |
} |
| 35 |
|
| 36 |
# main program |
| 37 |
BEGIN { |
| 38 |
if (ARGC < 3) { |
| 39 |
print "usage: translate from to" > "/dev/stderr" |
| 40 |
exit |
| 41 |
} |
| 42 |
FROM = ARGV[1] |
| 43 |
TO = ARGV[2] |
| 44 |
ARGC = 2 |
| 45 |
ARGV[1] = "-" |
| 46 |
} |
| 47 |
|
| 48 |
{ |
| 49 |
translate(FROM, TO) |
| 50 |
print |
| 51 |
} |