In a shell script I have a variable $PATH
which could look like this: /foo8232/test874-ab/bar/test-82-x
. I now want to get a substring of this, getting as a result test-82-x
in this specific case.
Thus I have to match the occurrences of /test.*
, but only the last element OR from the end of the string. Whatever works best.
Any help on this?
Edit:
Thanks for providing so many solutions so quickly. A few of them don't work though. Not sure, but maybe the problem is, that my path actually has whitespaces and more looks like this: /foo12323/test34 - 343bar/test - 234/test - 4323.txt
. Sorry that I didn't mentioned it in the fi开发者_如何学JAVArst place, if that causes troubles.
For your specific path management, you've got the basename function :
basename /foo8232/test874-ab/bar/test-82-x
>>> test-82-x
or in a script :
#!/bin/bash
fullfilename=$(basename $1)
extension=${fullfilename##*.}
filename=${fullfilename%.*}
echo "fullfilename=$fullfilename"
echo "extension=$extension"
echo "filename=$filename"
which gives :
./file_name.sh /foo8232/test874-ab/bar/test-82-x
fullfilename=test-82-x
extension=
filename=test-82-x
The following should be POSIX-compliant
BASE=$(basename $PATH)
if echo $BASE | grep "^test.*" > /dev/null; then
# do something awesome
fi
The last path element containing test
could also be found with sed
:
elem=$(echo $PATH | sed -r 's#.*/(test[^/]*).*#\1#')
Or without -r
(using extended regular expressions):
elem=$(echo $PATH | sed 's#.*/\(test[^/]*\).*#\1#')
So you're looking for the last directory component that starts with test
.
How about
IFS=/
for dir in $PATH; do
case $dir in test*)
match=$dir;;
esac
done
echo pwd | awk -F \/ '{print $NF}'|grep test
精彩评论