iwan
iwan

Reputation: 7569

Grab the filename in Unix out of full path

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?

Upvotes: 63

Views: 76550

Answers (5)

Milan Kerslager
Milan Kerslager

Reputation: 464

You may print all variables by this command (replace eth0 by real interface name):

for i in /sys/class/net/eth0/statistics/*; do echo -n "$(basename $i): "; echo -n $(cat $i); done

Upvotes: 0

kev
kev

Reputation: 161954

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

Upvotes: 93

Pavel Dolinin
Pavel Dolinin

Reputation: 21

You can use dirname command

$ dirname $path

Upvotes: 2

gbulmer
gbulmer

Reputation: 4290

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.

Upvotes: 6

tonymarschall
tonymarschall

Reputation: 3882

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

Upvotes: 2

Related Questions