Saturday, May 4, 2024
20
rated 0 times [  20] [ 0]  / answers: 1 / hits: 18100  / 1 Year ago, sun, february 12, 2023, 5:01:17

Is there any command which tells me in the specific directory which types of files exist?



I can find out the file type by using a command like od -c myfile | less.



But I don't know how to do it for all files in a directory.


More From » command-line

 Answers
6

Although od -c will indeed show the contents of a file, it is not a good way to get its file type. While some files will contain a header with the file type, not all will. A better way is the command file:



$ echo "hello" > foo.txt
$ file foo.txt
foo.txt: ASCII text


So, to get a list of all file types in a directory, you can do:



for file in dir/*; do file "$file" | cut -d: -f 2; done | sort -u


Example output:



 PNG image data, 1500 x 500, 8-bit/color RGBA, non-interlaced
ASCII text
directory
GIF image data, version 89a, 22 x 22
ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=becf821e4d814fdb69306d0b3f686eb06992f5e5, stripped


Explanation




  • for file in dir/*; do ... done; : iterate through everything in dir (dir is just an example, you should change this to the name of the actual directory you want to search through), saving each item in turn as $file

  • file "$file" : run file on each of the items found.

  • cut -d: -f 2 : print only the second field (fields defined by :)

  • sed 's/^ //; s/ +/ /g' : remove spaces from the beginning of the line and convert consecutive spaces into a single space.

  • sort -u : remove duplicate file types


[#26234] Monday, February 13, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
atelti

Total Points: 194
Total Questions: 129
Total Answers: 110

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
;