0

I want to get a path to a file location given a full path to that file in bash:

path="/home/user123/Documents/folder1/file1.txt

Given that full path I want to extract the "/home/user123/Documents/folder1" part. Should I just parse the path and throw away the part after the latest "/" or is there a better way?

Kooooro
  • 443
  • 1
  • 6
  • 15

2 Answers2

2

The dirname command in Linux will do that for you:

$ dirname /home/user123/Documents/folder1/file1.txt
/home/user123/Documents/folder1

To get the other piece, you can use basename:

$ basename /home/user123/Documents/folder1/file1.txt
file1.txt
gilez
  • 669
  • 3
  • 6
0

An alternative solution using sed:

 echo "$path" | sed 's/\(.*\)\/.*/\1/'
Jamil Said
  • 2,033
  • 3
  • 15
  • 18