Wednesday, October 7, 2009

Extract sub-string from variable in bash


Suppose:

$ mypath=/dir1/dir2/dir3/dir4

$ echo $mypath
/dir1/dir2/dir3/dir4

Now, if you need to print the parent path from the above path (i.e. print '/dir1/dir2/dir3')

$ dirname $mypath
/dir1/dir2/dir3

$ parentpath=$(dirname $mypath)

$ echo $parentpath
/dir1/dir2/dir3

Using Sub-string Removal ways in Bash shell

${string%substring}
It deletes shortest match of $substring from 'back' of $string.

$ echo ${mypath%/*}
/dir1/dir2/dir3

or

$ printf '%s\n' "${mypath%/*}"
/dir1/dir2/dir3

If you need to print the last directory name from the above mypath, here are few ways:

Using Sub-string Removal ways in Bash shell
${string##substring}
It deletes the "longest" match of $substring from 'front' of $string.

$ echo ${mypath##*/}
dir4

Another way using awk:

$ echo $mypath | awk '{print $NF}' FS=\/
dir4

Similar post:

- Truncate string using bash script

2 comments:

Ju. said...

Not a very good example, one could use basename.

$ mypath=/dir1/dir2/dir3/dir4
$ basename $mypath
dir4


But the ## trick is cool

pringi said...

Thanks man. It was a life saviour.

© Jadu Saikia www.UNIXCL.com