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 /home/guru/perl/file.pl1. The most commonly used is the basename command. basename command gives you the last component from the absolute path.
$ basename $y file.pl2. 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##*/} file.pl3. Using awk, we split using the delimiter slash(/) and print the last field($NF) which is the filename.
$ echo $y | awk -F"/" '{print $NF}' file.pl4. 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|.*/||' file.plAlso, 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|.*/||;' file.pl6. 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];' file.pl
Nice and very good explanation. Thanks for post. I tried all those. Awesome!
ReplyDeletethanks kaustubh
DeleteNice tut...can you please post one tutorial on "sudo".
ReplyDeleteThank you.
thanks anirvan..will do in future...
Delete