Linux check file info

Как определить тип файла файла с помощью Linux

Найдите тип файла любого файла или группы файлов с помощью команды FILE

Большинство людей смотрят на расширение файла, а затем угадывают тип файла с этим расширением. Например, когда вы видите файл с расширением gif, jpg, bmp или png, вы думаете о файле изображения, а когда вы видите файл с расширением zip, вы предполагаете, что файл был сжат с помощью утилиты сжатия zip ,

В действительности, файл может иметь одно расширение, но быть чем-то совершенно другим. В Linux вы узнаете истинный тип файла с помощью команды file .

Как работает команда File

Команда file выполняет три набора тестов для файла:

  • Тесты файловой системы
  • Магические тесты
  • Языковые тесты

Первый набор тестов для возврата правильного ответа приводит к печати типа файла.

Тесты файловой системы проверяют отдачу от системного вызова stat. Программа проверяет, является ли файл пустым и является ли он специальным файлом. Если тип файла найден в системном заголовочном файле, он возвращается как допустимый тип файла.

Магические тесты проверяют содержимое файла и, в частности, несколько байтов в начале, которые помогают определить тип файла. Различные файлы используются, чтобы помочь сопоставить файл с его типом файла, и они хранятся в:

Переопределите эти файлы, поместив файл в вашу домашнюю папку с именем $ HOME/.magic.mgc или $ HOME/.magic.

Финальные тесты – языковые тесты. Файл проверяется, чтобы увидеть, является ли он текстовым файлом. Тестируя первые несколько байтов файла, тест может определить, является ли файл ASCII, UTF-8, UTF-16 или другим форматом, который идентифицирует файл как текстовый файл. Когда выводится набор символов, файл проверяется на разных языках.

Если ни один из тестов не работает, выводом являются данные.

Как использовать команду «Файл»

Команда file может быть использована следующим образом:

Например, представьте, что у вас есть файл с именем file1, и вы запускаете следующую команду:

Вывод примерно такой:

Выходные данные определяют, что file1 – это файл изображения или, точнее, файл переносимой сетевой графики (PNG).

Различные типы файлов дают разные результаты:

  • Тип файла ODS : электронная таблица OpenDocument
  • Тип файла PDF : документ PDF, версия 1.4
  • Тип файла CSV : текст ASCII, с очень длинными строками, с индикаторами строк CRLF

Настройте вывод из команды File

По умолчанию команда file предоставляет имя файла и все детали над файлом. Если вы хотите, чтобы только детали без имени файла повторялись, используйте следующий переключатель:

Вывод примерно такой:

Вы также можете изменить разделитель между именем файла и типом. По умолчанию в качестве разделителя используется двоеточие, но вы можете изменить его на что угодно, например на символ канала, следующим образом:

Вывод примерно такой:

Обработка нескольких файлов

По умолчанию вы используете команду file для одного файла. Однако вы можете указать имя файла, которое содержит список файлов, которые будут обработаны командой file.

Например, откройте файл с именем testfiles с помощью редактора nano и добавьте в него следующие строки:

Сохраните файл и выполните следующую команду:

Результат будет примерно таким:

  • /etc/passwd: текст ASCII
  • /etc/pam.conf: текст ASCII
  • /etc/opt: каталог

Сжатые файлы

По умолчанию, когда вы запускаете команду file для сжатого файла, вы видите что-то вроде этого:

Хотя это говорит о том, что файл является архивом, вы не знаете его содержимого. Вы можете заглянуть внутрь zip-файла, чтобы увидеть типы файлов в сжатом файле. Следующая команда запускает команду file для файлов внутри ZIP-файла:

Читайте также:  Windows 10 32bit professional 20h2 compact

Вывод теперь показывает типы файлов файлов в архиве.

Большинство людей используют команду file, чтобы найти основной тип файла.Чтобы узнать больше о возможностях, которые предлагает команда file, введите в окне терминала следующее:

Эта команда открывает документацию по программному обеспечению Linux, включенную в систему.

Источник

7 Ways to Determine the File System Type in Linux (Ext2, Ext3 or Ext4)

A file system is the way in which files are named, stored, retrieved as well as updated on a storage disk or partition; the way files are organized on the disk.

A file system is divided in two segments called: User Data and Metadata (file name, time it was created, modified time, it’s size and location in the directory hierarchy etc).

In this guide, we will explain seven ways to identify your Linux file system type such as Ext2, Ext3, Ext4, BtrFS, GlusterFS plus many more.

1. Using df Command

df command reports file system disk space usage, to include the file system type on a particular disk partition, use the -T flag as below:

df Command – Find Filesystem Type

For a comprehensive guide for df command usage go through our articles:

2. Using fsck Command

fsck is used to check and optionally repair Linux file systems, it can also print the file system type on specified disk partitions.

The flag -N disables checking of file system for errors, it just shows what would be done (but all we need is the file system type):

fsck – Print Linux Filesystem Type

3. Using lsblk Command

lsblk displays block devices, when used with the -f option, it prints file system type on partitions as well:

lsblk – Shows Linux Filesystem Type

4. Using mount Command

mount command is used to mount a file system in Linux, it can also be used to mount an ISO image, mount remote Linux filesystem and so much more.

When run without any arguments, it prints info about disk partitions including the file system type as below:

Mount – Show Filesystem Type in Linux

5. Using blkid Command

blkid command is used to find or print block device properties, simply specify the disk partition as an argument like so:

blkid – Find Filesystem Type

6. Using file Command

file command identifies file type, the -s flag enables reading of block or character files and -L enables following of symlinks:

file – Identifies Filesystem Type

7. Using fstab File

The /etc/fstab is a static file system info (such as mount point, file system type, mount options etc) file:

Fstab – Shows Linux Filesystem Type

That’s it! In this guide, we explained seven ways to identify your Linux file system type. Do you know of any method not mentioned here? Share it with us in the comments.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How to Determine the File Type of a File Using Linux

Find the file type of any file or group of files with the ‘file’ command

Most people look at the extension of a file and then guess the type of file from that extension. For example, when you see a file with an extension of gif, jpg, bmp, or png you think of an image file, and when you see a file with an extension of zip, you assume the file has been compressed using a zip compression utility.

A file can use one extension but be something altogether different. Linux doesn’t use file extensions; rather, the file’s type is part of the file name. To find out the true file type use the file command.

How the ‘file’ Command Works

The file command runs three sets of tests against a file:

  • Filesystem tests
  • Magic tests
  • Language tests
Читайте также:  Компьютер долго перезагружается что делать для windows

The first set of tests to return a valid response prompts the file type to be printed.

Filesystem tests examine the return from a stat system call. The program checks to see if the file is empty and whether it is a special file. If the file type is found in the system header file, it is returned as the valid file type.

The magic tests check the contents of a file and specifically a few bytes at the beginning that help to determine the file type. Various files are used to help match up a file with its file type, and these are stored in:

  • /etc/magic
  • /usr/share/misc/magic.mgc
  • /usr/share/misc/magic

Override these files by placing a file in your home folder called $HOME/.magic.mgc or $HOME/.magic.

The final tests are language tests. The file is checked to see if it is a text file. By testing the first few bytes of a file, the test deduces whether the file is an ASCII, UTF-8, UTF-16, or another format that identifies the file as a text file. When the character set is deduced, the file is tested against different languages.

How to Use the ‘file’ Command

The file command takes the following form:

The output will be something like this:

  • /etc/passwd: ASCII text
  • /etc/pam.conf: ASCII text
  • /etc/opt: directory

Standard wildcards work, too. For example, to test all files in the present working directory, use:

To test for directories that start with the letter D (case sensitive) try this:

The results could be Desktop, Documents, and Downloads, for example.

Compressed Files

When you run the file command against a compressed file you see output something like this:

  • file.zip: ZIP archive data, at least V2.0 to extract

While this result tells you that the file is an archive file, you don’t know the contents of the file. Look inside the zip file to see the file types of the files within the compressed file. The following command runs the file command against the files inside a ZIP file:

file -z filename

The output now shows the file types of files in the archive.

Источник

Beginner Linux Tutorial

Linux File Info Command

The Linux file command is a pretty basic command in Linux that will output the file type information onto your screen. There are quite a few options for the Linux file info command, but I only use maybe 2 of the options on a regular basis. With Microsoft Windows it will always think that the extension of he file determines the file type. If you have a file named filename.txt Windows will automatically think this file type is a text file, when it could actually be a pdf file with a bad extension on it! Now Linux on the other hand, if you come across a file that has a bad extension on it, you can run file filename.txt and it will output: filename.txt: PDF document, version 1.4 or whatever version of the pdf format it actually is.

The main options of the file command that I use is file -f [filename] , where [filename] would be a standard text file with a list of files you want to have checked. If using this option you will want [filename] to have 1 filename per line.

The other option I use often isn’t really an option on the file command, but is a short script. You can run file `ls` and it will output the file types of all of the files that the ls command outputs normally, which will be all of the files listed in your current working directory.

I hope this Linux tutorial for beginners has helped you learn more about the Linux file type information command. As always if you have any questions or comments on this Linux tutorial you can leave them below, or you can use our Linux forum.

Источник

5 Commands to View the Content of a File in Linux Command Line

If you are new to Linux and you are confined to a terminal, you might wonder how to view a file in the command line.

Reading a file in Linux terminal is not the same as opening file in Notepad. Since you are in the command line mode, you should use commands to read file in Linux.

Читайте также:  Завис значок загрузки windows 10

Don’t worry. It’s not at all complicated to display a file in Linux. It’s easy as well essential that you learn how to read files in the line.

Here are five commands that let you view the content of a file in Linux terminal.

5 commands to view files in Linux

Before you how to view a file in Unix like systems, let me clarify that when I am referring to text files here. There are different tools and commands if you want to read binary files.

1. Cat

This is the simplest and perhaps the most popular command to view a file in Linux.

Cat simply prints the content of the file to standard display i.e. your screen. It cannot be simpler than this, can it?

cat displays the content of the file on the screen

Cat becomes a powerful command when used with its options. I recommend reading this detailed tutorial on using cat command.

The problem with cat command is that it displays the text on the screen. Imagine if you use cat command with a file that has 2000 lines. Your entire screen will be flooded with the 200 lines and that’s not the ideal situation.

So, what do you do in such a case? Use less command in Linux (explained later).

The nl command is almost like the cat command. The only difference is that it prepends line numbers while displaying the text in the terminal.

nl command displays text with line numbers

There are a few options with nl command that allows you to control the numbering. You can check its man page for more details.

3. Less

Less command views the file one page at a time. The best thing is that you exit less (by pressing q), there are no lines displayed on the screen. Your terminal remains clean and pristine.

I strongly recommend learning a few options of the Less command so that you can use it more effectively.

There is also more command which was used in olden days but less command has more friendly features. This is why you might come across the humorous term ‘less is more’.

4. Head

Head command is another way of viewing text file but with a slight difference. The head command displays the first 10 lines of a text file by default.

You can change this behavior by using options with head command but the fundamental principle remains the same: head command starts operating from the head (beginning) of the file.

5. Tail

Tail command in Linux is similar and yet opposite to the head command. While head command displays file from the beginning, the tail command displays file from the end.

By default, tail command displays the last 10 lines of a file.

Head and Tail commands can be combined to display selected lines from a file. You can also use tail command to see the changes made to a file in real time.

Bonus: Strings command

Okay! I promised to show only the commands for viewing text file. And this one deals with both text and binary files.

Strings command displays the readable text from a binary file.

No, it doesn’t convert binary files into text files. If the binary file consists of actual readable text, strings command displays those text on your screen. You can use the file command to find the type of a file in Linux.

Conclusion

Some Linux users use Vim to view the text file but I think that’s overkill. My favorite command to open a file in Linux is the less command. It leaves the screen clear and has several options that makes viewing text file a lot easier.

Since you now know ways to view files, maybe you would be interested in knowing how to edit text files in Linux. Cut and Paste are two such commands that you can use for editing text in Linux terminal. You may also read about creating files in Linux command line.

Источник

Оцените статью