(?) The Answer Gang (!)


By Jim Dennis, Ben Okopnik, Dan Wilder, the Editors of Linux Gazette... and You!
Send questions (or interesting answers) to [email protected]


(?) Question in shell programming

From Jane Liu

Answered By Dan Wilder, Jim Dennis

I wanted to change the first letter of each line to upper case? How can I do it with awk?

Thanks, Jane

(!) [Dan] Here's one way:
#!/usr/bin/awk -f

{
a = substr($0, 1, 1)
b = toupper(a)
sub(a, b, $0)
print
}
"a" has the length-1 substring of the current input record, $0, beginning at the first character of the input line.
"b" has the upper-case equivalent of "a".
"sub" substitutes what's in "b" in place of the first match in the string for what's in "a". The third argument to "sub" may be left implicit, but I prefer not to do so, feeling that putting $0 in makes the operation of the program more obvious at a glance.
(!) [JimD] Here's a simple one liner:
awk '{ sub(/^./,toupper(substr($0,1,1))); print; }'
... substitute the first character of the implicit pattern space ($0) with the value returned by the "toupper()" function, when it's called on the substring of $0 (the default pattern space) from the first character and continuing for one character.
Then print the thing.
Can't get much simpler than that.

(?) Thanks a lot! It works perfectly.

Thanks again!
Jane


This page edited and maintained by the Editors of Linux Gazette Copyright © 2001
Published in issue 64 of Linux Gazette March 2001
HTML script maintained by Heather Stern of Starshine Technical Services, http://www.starshine.org/


[ Answer Guy Current Index ] greetings   1   2   3   4   6   7   9 [ Index of Past Answers ]
11   12   15   16   18
20   22   24   25   26   28   29