I have a file path.txt with the path to a file(say a txt file):


I want to extract the path i.e the string from beginning to the last occurrence of / (since the number of folder in path may vary).

I want to get:


Which would be the best choice: sed/awk/perl/vi and how?


If you want to use one of those tools you mentioned, you can do it with sed:

echo "/Folder/F1/F2/F3/F4/.../Fn/abc.txt" | sed "s/\/[^/]*$//"
sed -i "s/\/[^/]*$//" path.txt

If you are in bash, you can use Bash parameter expansion for this:

path=$(cat path.txt)
echo "${path%/*}"

And as mentioned by ikkachu you can use dirname.


basename and dirname print the last and all-but-last parts of a filename given as argument, so:

$ dirname "/Folder/F1/F2/F3/F4/.../Fn/abc.txt" 

(or from a file: dirname "$(< pathname.txt)" )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.