Note: this doesn't just answer the OP's question. Rather, it also answers the generic question posed by just the title of this question:
Grabbing the extension in a file name
To answer the OP:
echo "/dir/subdir/file-1.0.tar.bz2" \
| sed 's/.*\///' | grep -oE "\.[^0-9]*\..*$"
Output:
.tar.bz2
The sed
part obtains just the string after the last /
, and the grep
part obtains the extension beginning with a period (\.
), any number of chars not containing a number ([^0-9]*
), and then a period followed by any char to the end of the line (\..*$
).
General answer: how to extract just the extensions from a multi-line string containing a bunch of filenames
...including extracting more-complicated extensions, such as .tar.gz
from file.10.5.2.tar.gz
(basically just ignoring numeric 0-9 portions of extensions).
I really like this solution, piping the filenames to sed 's/.*\///' | grep -oE "(^[^.]*$|\.[^0-9]*\..*$)" | sort -u
. The grep
regex portion of the answer is pretty complicated because it needs to remove the portion of the extensions which contain numbers 0-9.
Example:
filenames_str="\
/some/file.txt
/whatever/prog.c
/something/abc.tar.bz
/something/abc.123.456.789.tar.bz
/something/abc.c
/something/abc.h
/path/to/file.10.5.2.tar.gz
/path/to/file.10.5.2.tar.gz.whatever
/path/to/file.10.5.2.tar.gz.whatever.7.pdf
/noextension"
echo "$filenames_str" \
| sed 's/.*\///' | grep -oE "(^[^.]*$|(\.[^0-9])*(\.[^0-9]*$))" | sort -u
Output:
.c
.h
noextension
.pdf
.tar.bz
.tar.gz
.tar.gz.whatever
.txt
Explanation, from my answer here (although the above is modified from my other answer, to answer the OP's question above as well): All about finding, filtering, and sorting with find
, based on file size:
The sed
part retains just the contents after the last /
. The grep
part then keeps only the extension, including the dot (.
), if it has one, and the whole string otherwise. And finally, sort -u
removes duplicates to leave only unique strings.