How to extract text from an environment variable?

I have a my-variable-here environment variable, e.g.
Code:
my-variable-here=/var/log/test
I want to get the text between the equal sign and the 2nd second slash. So in my example above, I want to get the text "/var". How do I do it?

Thanks very much.
 
Very quick and dirty without sed (which would be more elegant):

Code:
$ export my="/var/log/test"
$ echo $my
/var/log/test
$ echo "/$(echo $my | cut -d "/" -f2)"
/var
 
There's also sh(1) "Parameter Expansion". See man sh | less -p 'Remove Largest Suffix Pattern', although right now I can't think of an appropriate pattern to leave just the first directory name for an arbitrary-length path. It could also be done with multiple calls to basename(1)/dirname(1).
 
Code:
#!/bin/sh
expr "/this/that/somthing/else/over/there" : '\/\([[:alpha:]]\{1,\}\)'
returns
this

expr "/this/that/somthing/else/over/there" : '\(\/[[:alpha:]]\{1,\}\)'
returns
/this

Better late than never... :)
 
shell only without external commands
Code:
#!/bin/sh
##############v1##############
a=/var/log/messages
IFS=/
set -- $a
echo /$2
unset IFS
####v2############################3
a=/var/log/message
a=${a#/}
a=${a%%/*}
echo /$a
 
Back
Top