简体   繁体   中英

Unix Command to get file path without basename

I have following file in unix directory

/home/files/myfiles/good.txt

I need to extract the file path alone

Expected output : /home/files/myfiles

Note : I can not use cut operations as the file path is dynamic. I am getting the filename and filepath as single user input to the shell script

尝试

$ dirname /home/files/myfiles/good.txt

应该做的工作:

echo /home/files/myfiles/good.txt | sed s,/*[^/]*$,,

Without spawning another process, you can use parameter expansion :

file=/home/files/myfiles/good.txt
echo "${file%/*}"
/home/files/myfiles

FWIW, cut CAN do it dynamically with a little help of rev

$ echo "/home/files/myfiles/good.txt" | rev | cut -d/ -f2- | rev
/home/files/myfiles

$ echo "/home/files/myfiles/yourfiles/good.txt" | rev | cut -d/ -f2- | rev
/home/files/myfiles/yourfiles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM