Wednesday, September 17, 2008

How do i get ONLY filename from given path of the file

Ok , so i was given a file path such as "home/user/scripts/test.sh" and i need to retrive only the filename "test.sh".

It is awesome to come with solution using awks and seds commands, but then for some lazy guys around like me, UNIX has given something below

$ basename /home/user/scripts/test.sh

well, basename is command used which would return you back filename(no matter how long the path is) as output when you execute the command in above fashion and the output of above command would be "test.sh"

OK, now what if i need only "test" and want to delete the extension.

$ basename /home/user/scripts/test.sh .sh

and the output is "test" in above command.

You could use the same command in scripts where in at times it becomes necessary to access only the filenames from a path OR places where the file extension needs to be changed.

No comments: