-1

Let's say I have a string which represents the full path of a file: full_path='./aa/bb/cc/tt.txt'.

How can I extract only the file name tt.txt?

Please don't tell me to use echo $full_path | cut -d'/' -f 5.

Because the file may be located in a deeper or shallower folder.

The number, 5, cannot be applied in all cases.

Brian
  • 12,145
  • 20
  • 90
  • 153

3 Answers3

0

if you are comfortable with python then, you can use the following piece of code.

full_path = "path to your file name"
filename = full_path.split('/')[-1]
print(filename)
Shubham Jaiswal
  • 359
  • 1
  • 9
0

Use the parameter expansion functionality.

 full_path='./aa/bb/cc/tt.txt'
 echo ${full_path%/*}

That will give you the output

 ./aa/bb/cc

And will work any number of directory levels deep, as it will give you everything up to the final "/".

Edit: Parameter expansion is very useful, so here's a quick link for you that gives a good overview of what is possible: http://wiki.bash-hackers.org/syntax/pe

michjnich
  • 2,796
  • 3
  • 15
  • 31
0

You can use this construct

echo "$full_path" | sed 's/\/.*\///'
webmite
  • 575
  • 3
  • 6