-   Programming (
-   -   bash + string manipulation (

dave bean 02-15-2005 06:52 AM

bash + string manipulation
I have the following string stored in a variable:


[Requesting program interpreter: /lib/]
I want to isolate and store this value in a variable, I don't want to rely on using character numbers to make a substring becasue the text part may vary from distro to distro, i want to seach the string until '/lib/' then cut out the linker ( finishing at ']'

How would i go about this and what tool ie grep, sed, etc should i use ?


druuna 02-15-2005 07:15 AM


This is one way, using sed:

echo "[Requesting program interpreter: /lib/]" | sed 's%.*/lib/\(.*\)]%\1%'

Hope this helps

crabboy 02-15-2005 09:38 AM

I like the sed solution, but here it is with cut and basename:

basename `echo "[Requesting program interpreter: /lib/]" |  cut -d: -f2 | cut -d']' -f1 `

LasseW 02-15-2005 10:01 AM

Or use expr with a regexp. This is very similar to druna's solution:

$ VAR1='[Requesting program interpreter: /lib/]'
$ VAR2=$(expr "$VAR1" : '.*/lib/\(.*\)]')
$ echo $VAR2

dave bean 02-15-2005 11:35 AM

Thanks for the replies, I used sed finally, cos i understood the command and im trying to get to grips with it ;)

crabboy, would you mind explaining how your command works, i took a look at the info pages of cut
and basename but i still don't understand it :scratch:

The other thing is, i was wondering if theres a way to simulate the running of a shell script to ascertain if there are bugs etc
I don't want half the script to execute and then crash out leaving everything half done.


druuna 02-16-2005 07:35 AM


If you need any (extra) help with the sed command, just let me (us) know.

About the command crabboy gave (don't think he minds me explaining it):

basename `echo "[Requesting program interpreter: /lib/]" | cut -d: -f2 | cut -d']' -f1 `

basename will strip directories and suffix from filename so basename /path/to/program will give you program.

So only the /lib/ part of the variable you gave ( [Requesting program interpreter: /lib/] ) should be given to basename. The echo and the 2 cut statements do this.

cut -d: -f2 sets the delimiter to : and prints the second (-f2) field. You will end up with:


Looks nice, but there's still a ] at the end of the string. The leading space(s) can be ignored.

cut -d']' -f1 sets the delimiter to ] ( -d']' ) and print the first field ( -f1 ). You will end up with:

Because the part between ` and ` (backquotes) will be done first by the shell the command after the execution of the `echo|cut|cut` commands looks like this:

basename /lib/, which in term prints:

Hope this clears things up a bit.

crabboy 02-16-2005 10:10 AM

Thanks druuna, well done.

dave bean 02-16-2005 11:16 AM

ahh, thanks a lot druuna, that was good of you ;)

I also sussed what you was talking about before about using 'sh -x' and 'sh -n' ;)


All times are GMT -5. The time now is 04:39 PM.