DamienzOnly
DamienzOnly

Reputation: 88

Recognize files depending on extension

i need to recognize files with different extensions even when there is a combination of multiple extensions
so if my cwd has this files:

file-1 .zip
file-2 .tar
file-3 .tar.gz
file-4 .gz
file-5 .zip.tar
file-6 .tar.gz
file-7 .gz

i need to tell bash what to do when the extension (in this case) is:


because for every extension i need to do different things, this implies that if the extension is .tar (only) or .gz (only) i need to do certain things, but if the extension is .tar.gz i need to run another snippet.

example: if the filename has .tar extension i need to do

# stuff
tar xf filename.tar
# other stuff

if the filename has .zip.tar extension i need to run more complex code (but the code is not totally dependent on the extensions, my only objective is to get the full extension of the filename (filename.tar.gz should return .tar.gz instead of .gz or .tar)

Also, is there any way using gawk?

Upvotes: 1

Views: 136

Answers (2)

LMC
LMC

Reputation: 12787

The file command is a good option to detect file types, then you can write a logic

file -i test.*

test.gz:     application/x-gzip; charset=binary
test.tar:    application/x-tar; charset=binary
test.tar.gz: application/x-gzip; charset=binary
test.zip:    application/zip; charset=binary

Upvotes: 0

Barmar
Barmar

Reputation: 782107

Use case:

case "$filename" in 
    *.tar.gz) code for .tar.gz ;;
    *.gz) code for .gz ;;
    *.zip.tar) code for .zip.tar ;;
    *.tar) code for .tar ;;
    ...
esac

Just make sure you put the combined extensions before the single extensions that they contain, because case executes the statements for the first pattern that matches.

Upvotes: 3

Related Questions