need AWK help: lowercase, trim trailing spaces

Mark Harrison harrison at necssd.NEC.COM
Wed Apr 24 01:37:06 AEST 1991


In article <1817 at wjvax.UUCP>, mario at wjvax.UUCP (Mario Dona) writes:

> HELP! I have a situation that just cries out for an awk solution

[converting from]

> COMPANY1  2800 FULLING       P O BOX 3608     HARRISBURG PA           17105

[to] 

> Company1
> 28 Fulling
> P O Box 3608
> Harrisburg PA 17105

> 1.  How to prevent blank lines from printing if there is nothing to print

Add this line after your BEGIN rule:
/^$/ {next} #skip blank lines

If you want to skip lines that may have white space:
/^[ \t]*$/ {next} #skip blank (non-text) lines

> 2.  How to concatenate the city and zip fields as shown.

To concatenate:

	city_and_zip = city " " zip

To strip trailing space from city before concatenating:

	while (substr(city, length(city)) == " ")
		city = substr(city, 1, length(city) - 1)

> 3.  If a word is greater than 2 characters, lowercase all letters
>     except for the first character (this is to keep state capitols 
>     capitalized).

This is doable, but not enjoyable.  There is more of a chance if
you use nawk or gawk. Otherwise, make an array:

uc["a"] = "A"  ... uc["z"] = "Z"
lc["A"] = "a"  ... lc["Z"] = "z"

and loop for the length of the string:

    if (uc[substr(str, i, 1)] == "")
        newstr = newstr substr(str, i , 1)
    else
        newstr = uc[substr(str, i, 1)]



More information about the Comp.unix.questions mailing list