Reputation: 20774
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 (i.e., 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?
Upvotes: 1
Views: 697
Reputation: 785276
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")
Upvotes: 3
Reputation: 3194
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
$
Upvotes: 2