Tuesday, April 3, 2012

Different ways to get the filename from absolute path

   In this article, we will see the different ways from which we can get the filename from an absolute path name. Assume a variable "y" which contains the absolute path. Let us see how to extract the filename alone from the absolute path.
$ echo $y
1. The most commonly used is the basename command. basename command gives you the last component from the absolute path.
$ basename $y
2. This is the best of all since it uses no external command.  '##' tells to match the longest pattern from the beginning, and the pattern is '*/'. And hence, the entire thing till the last slash(/) gets removed and the filename remains.
$ echo ${y##*/}
3. Using awk, we split using the delimiter slash(/) and print the last field($NF) which is the filename.
$ echo $y | awk -F"/" '{print $NF}'
4. Using sed, we remove everything from the beginning till the slash. Due to the greedy nature of sed, it gobbles all the way till the last slash and not till the first slash, and hence the filename.
$ echo $y  | sed 's|.*/||'
    Also, the thing to be noted here is the substitution separator. It is not mandatory to always use slash(/) after s. "|" is used instead. Slash(/) is not used here since our regular expression contains / , and we would have had to escape it had we used it the normal way.

5. Same as sed, but using perl.
$ echo $y | perl -pe 's|.*/||;'
6. One more with Perl. Here, we autosplit the file(-a) with the slash as delimiter(-F). Once split, the individual fields will be in the perl special arry @F.  $#F gives the length of the array, and $F[$#F] gives the last element of the array which is the file name.
$ echo $y | perl -F[/]  -ane 'print $F[$#F];'


  1. Nice and very good explanation. Thanks for post. I tried all those. Awesome!

  2. Nice tut...can you please post one tutorial on "sudo".
    Thank you.