简体   繁体   中英

Get parent directory name and filename without extension from full filepath in bash?

I have a long file path, like

 /path/to/file/dir1/dir2/file.txt.gz

I am interested in getting the file name without the last extension (ie, file.txt ), and the name of the parent directory ( dir2 , I don't want the full path to the parent directory, just its name).

How can I do this in bash?

Using BASH:

s='/path/to/file/dir1/dir2/file.txt.gz'

file="${s##*/}"
file="${file%.*}"
echo "$file"
file.txt

filder="${s%/*}"
folder="${folder##*/}"
echo "$folder"
dir2

Using awk :

awk -F '/' '{sub(/\.[^.]+$/, "", $NF); print $(NF-1), $NF}' <<< "$s"
dir2 file.txt

To read them into shell variables:

read folder file < <(awk -F '/' '{sub(/\.[^.]+$/, "", $NF);print $(NF-1), $NF}'<<<"$s")

The first part can be solved by basename(1):

$ basename /path/to/file/dir1/dir2/file.txt.gz
file.txt.gz
$ 

dirname(1) does the opposite, which is not quite what you want, but maybe you can use that as a starting point:

$ dirname /path/to/file/dir1/dir2/file.txt.gz
/path/to/file/dir1/dir2
$ 

Of course, you can always use Perl:

$ perl -E 'do { @p=split m|/|; say $p[-2] } for @ARGV' /path/to/file/dir1/dir2/file.txt.gz
dir2
$ 

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