Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab the filename in Unix out of full path

Tags:

bash

shell

unix

ksh

I am trying to get "abc.txt" out of /this/is/could/be/any/path/abc.txt using Unix command. Note that /this/is/could/be/any/path is dynamic.

Any idea?

like image 417
iwan Avatar asked Apr 12 '12 13:04

iwan


People also ask

How do I get only the filename in Unix?

If you want to display only the filename, you can use basename command. find infa/bdm/server/source/path -type f -iname "source_fname_*. txt" Shell command to find the latest file name in the command task!

How do I get the full path of a filename?

Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).

How do you get the full path of a file in Unix?

To use this command, simply type “readlink -f ” into your terminal then, type in the name of the file or folder that you want to find the path for and press enter. The output will be the file path of the specified file or folder.


2 Answers

In bash:

path=/this/is/could/be/any/path/abc.txt 

If your path has spaces in it, wrap it in "

path="/this/is/could/be/any/path/a b c.txt" 

Then to extract the path, use the basename function

file=$(basename "$path") 

or

file=${path##*/} 
like image 121
kev Avatar answered Sep 26 '22 00:09

kev


basename path gives the file name at the end of path

Edit:

It is probably worth adding that a common pattern is to use back quotes around commands e.g. `basename ...`, so UNIX shells will execute the command and return its textual value.

So to assign the result of basename to a variable, use

x=`basename ...path...` 

and $x will be the file name.

like image 40
gbulmer Avatar answered Sep 25 '22 00:09

gbulmer