String Manipulation Help

Hey Guys,

Right i know how to alter a word to begin with a capital letter, i know how to remove unwanted characters and replace them with the relevant character however i don't now if there is a way to do them all in one line.

Code:

echo -n ${string:0:1} | tr a-z A-Z #convert first letter in string to cap
echo ${string:1} # to remove first char & replace with cap from above
echo ${string/<char>/<char>} # to replace a character

What i would like to know, is there a way i can Join the second statement with the first .. So i can begin at the string from the second letter and at the same time omit unwanted characters.

Thanks in advance!

Nobody ever specifies which language. :frowning: Oh well, everybody uses ksh exclusively, right? :slight_smile:

$ cat cap
#! /usr/bin/ksh

typeset -L1 -u first
name="henry"
first=$name
newname=${first}${name#?}
echo $name $newname
$ ./cap
henry Henry
$

To get it to one line, I used awk...

$ cat awkcap
#! /usr/bin/ksh

L="abcdefghijklmnopqrstuvwxyz"
U="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
echo 'henry' | awk -v u=$U -v l=$L '{print substr(u,index(l,substr($0,1,1)),1) substr($0,2);}'
$ ./awkcap
Henry
$

The L and U variables could disappear and you could put the strings directly into the awk statement if you feel that I cheated by using those variables. But that makes for a very long statement.

#! /usr/bin/ksh

echo 'henry' | awk -v u="ABCDEFGHIJKLMNOPQRSTUVWXYZ" -v l="abcdefghijklmnopqrstuvwxyz" '{print substr(u,index(l,substr($0,1,1)),1) substr($0,2);}'

I prefer the first version, but the second is strictly "one line" as requested.

Yep i knew i forgot to mention something, I'm using bash for this script. That probably means that the code there wont be work for me. After having a break I'm gonna get back on it know to see if i can do anything.

An example of what I'm trying to do (ill use your name example):

string is john#long.smith

So the currently my code removes unwanted characters leaving white spaces in their place, changes the first character to caps however i would want to change each new word to begin with a cap.

so output: John Long Smith - hope you can help! :slight_smile: Ill be working on it in the mean time and get back if i find something.

Thanks!

I edited my earlier post to fix a couple of letters that needed swapping. At this point you are asking a lot for one line of code! But...

#! /usr/bin/ksh

L="abcdefghijklmnopqrstuvwxyz"
U="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
echo 'i%%%%long $$$john&&&&&&  ((())) silver' |\
sed 's/[^a-zA-Z]/ /g;s/  */ /g'| awk -v u=$U -v l=$L '{for (i=1;i<=NF;i++)printf "%s%s ",substr(u,index(l,substr($i,1,1)),1),substr($i,2);print "";}'

seems to be working. I retreated to my preferred syntax where the long constants are out of the awk script.You can put them back if you really want to keep it to one line. Test run:

$ ./awkcap
I Long John Silver
$