regex to match basename

Hi

Can somebody please help me know how do i match the basename using a regular expression using posix standard in shell script

suppose i want to match

/u01/Sybase/data/master.dbf the result should be master.dbf as i want to match everything after the last /

regards

 echo /u01/Sybase/data/master.dbf | grep -o '[^/]*$'

If u make a little search, you could have found the answer yourself...

 
>str="/u01/Sybase/data/master.dbf "
>echo ${str##*/}
>master.dbf

>str="/u01/Sybase/data/master.dbf"
>echo $str
/u01/Sybase/data/master.dbf
>basename $str
master.dbf

Hi

Thanks to all responded and the responses are also excellent at this point of time i am very keen on the regex solution

 echo /u01/Sybase/data/master.dbf | grep -o '[^/]*$'

due to my inquisitiveness in regex what does this regex do

grep -o '[^/]*$'

I know individually
^ matches begining of the line
$ matches end of the line

  • matches anything
    

/ is a escape sequence

i dont understand what a [] does and what does the combined expression all put together mean including the greps -o switch

I'll try to explain it:

[^/]*$

is called a bracket expression (see man grep).

^ as first character within the bracket expression means: don't match characters within the brackets

[^/] means select all characters except a slash

*$ means match the characters untill the last character

Thus the whole regex means: select all the characters till the end without a slash.

Regards

Hi Franklin

Thank you for the excellent explanation.

However what does the -o do it doesnt sem to work on AIX

when i do

echo /u01/Sybase/data/master.dbf | grep '[^/]'

shoudlnt it return everything minus the / slash in my case it returns

u01 Sybase data master.dbf

regards

another solution :

 echo "/u01/Sybase/data/master.dbf" |sed 's:.*/::g' 

in that command : sed 's:<old value>:<new value>:g' substitute the old value with the new value

. means any character or number

  • matches the previous character set zero or more times
    the new value is null
    g means global replacement, replace the old value by the new one everytime u see it
    Thus, the whole expression is translated to : substitute anything followed by a slash with "nothing"
    So it deletes the path and u'll get the basename.

Hope that helps.

Have a read of this regarding regular expressions:

Regular Expression Tutorial - Learn How to Use Regular Expressions

Regards