Grab the filename in Unix out of full path

BashShellUnixKsh

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

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##*/}

Solution 2 - Bash

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.

Solution 3 - Bash

You can use dirname command

$ dirname $path

Solution 4 - Bash

You can use basename /this/is/could/be/any/path/abc.txt

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioniwanView Question on Stackoverflow
Solution 1 - BashkevView Answer on Stackoverflow
Solution 2 - BashgbulmerView Answer on Stackoverflow
Solution 3 - BashPavel DolininView Answer on Stackoverflow
Solution 4 - BashtonymarschallView Answer on Stackoverflow