Computing.Net > Forums > Unix > Substrings in Unix

Substrings in Unix

Reply to Message Icon

Original Message
Name: Jon Moore
Date: June 6, 2005 at 07:39:25 Pacific
Subject: Substrings in Unix
OS: Unix
CPU/Ram: 200/256
Comment:

Hi All,

I am having a problem extracting part of a string into a variable using korn shell. Using the id command the following is returned and stored in a variable called userid:

uid=2435(TY34955) gid=34543(systems)

I need to extract the (TY34955) without the braces when the length of both the uid(the 2435) and and the(TY34955) may vary.

example of desired output:
TY34955

Is there a good way to do this?

Thanks,
Jon


Report Offensive Message For Removal


Response Number 1
Name: Jim Boothe
Date: June 6, 2005 at 08:26:37 Pacific
Reply: (edit)

You can use a two-step process where the first step removes from the beginning and the second step removes from the end:

name1=${userid#*\(}
name2=${name1%%\)*}

Or this will pull it in one step:

name2=$(expr "$userid" : ".*(\(.*\)) gid=")

On HP-UX, I use this instead:

name2=$(whoami)


Report Offensive Follow Up For Removal

Response Number 2
Name: Jim Boothe
Date: June 6, 2005 at 08:31:56 Pacific
Reply: (edit)

And not nearly as efficient, but awk can pull it as the second field where fields are delimited by either left or right parentheses:

name2=$(echo $userid | awk -F "[()]" '{print $2}')


Report Offensive Follow Up For Removal

Response Number 3
Name: nails
Date: June 7, 2005 at 08:52:10 Pacific
Reply: (edit)

There's numerous ways of doing this, here is another:

#!/bin/ksh

uid=$(id | cut -d'(' -f2 | cut -d')' -f1)



Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Substrings in Unix

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes In 6 Days.
Discuss in The Lounge