-1

I have a file that does not have an extension and would like to add an extension to it programmatically. I know the file command gives information about the extension of a file. How can I utilize this to add the extension to a file? The files I'm downloading can be assumed to be image files (png, jpg, etc.)

My desired outcome would be:

Input: filename

Output: filename.ext

All inside a bash script

abden003
  • 1,325
  • 7
  • 24
  • 48

2 Answers2

2

Something like this should get you started:

#!/bin/bash
for f in "$@"; do
    if [[ $f == *'.'* ]]; then continue; fi  # Naive check to make sure we don't add duplicate extensions
    ext=''
    case $(file -b "$f") in
        *ASCII*) ext='.txt' ;;
        *JPEG*)  ext='.jpg' ;;
        *PDF*)   ext='.pdf' ;;
        # etc...
        *) continue ;;
    esac
    mv "${f}" "${f}${ext}"
done

You'll have to check the output of file for each potential file type to find an appropriate case label.

0x5453
  • 12,753
  • 1
  • 32
  • 61
0

You can try to find or create a map of file-type to file extension name but there's no universal way. Think about JPEG images, you can either have .jpg or .jpeg extension, and they both mean the same thing. Same for MP4 video containers...

Also, on linux the file extension doesn't even matter to most programs so you could just not care about it, but if you still want to do it for certain types of files, you can check this answer : https://stackoverflow.com/a/6115923/9759362

Zyfarok
  • 1
  • 1