See file information linux

Linux And Unix Command To View File

Linux And Unix Command To View File

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux or Unix system
Est. reading time 2m
  • cat command
  • less command
  • more command
  • gnome-open command or xdg-open command (generic version) or kde-open command (kde version) – Linux gnome/kde desktop command to open any file.
  • open command – OS X specific command to open any file.

View a text file called foo.txt on a Linux or Unix-like systems

Open the Terminal application and type the following command to view a text file called foo.txt using cat command:
cat foo.txt
OR
cat /etc/resolv.conf
Sample outputs:

You can also use more or less command as follows:

gnome-open: Open files and directories/urls

The gnome-open command opens a file (or a directory or URL), just as if you had double-clicked the file’s icon. The syntax is:

If you are using KDE desktop try kde-open command as follows:

Another option is to try out xdg-open command on Linux and Unix desktop:

If you are using OS X Unix try open command as follows:

How do I list the files in a directory on Unix?

To see or list the files in a directory on Linux, run ls command:
ls
ls -l
If you would like to see and list files in another directory, use the ls along with the path to the directory:
ls /usr/
ls -l /etc/
## just list resolv.conf file #
ls -l /etc/resolv.conf

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Common ls command options

The syntax is:
ls [options] file
Where options for ls are:

  • -l : Use a long listing format to display Linux/Unix file names.
  • -a : Do not ignore entries starting with . (period). Display all hidden files.
  • -d : List Linux directories themselves, not their contents
  • -R : List sub-directories recursively on Linux
  • -F : Append indicator for file. For example, / for directories, * for executable Linux files, @ for symbolic links and more

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Sometimes the ‘ strings ‘ command is useful if the file is not all text. I seems to pull out text but leave the no text out.

Don’t forget: tac

Although I’ve yet to find a useful purpose for it

this sucks to high heaven,,linix is a pain in arse,,i dont know why anyone would use a fool system like this,,terminals suck,,i do mwean suck. terminals. idiots,,my windows got imploded,,i had to download this ubuntu,,i regret every god dam day of it,,i cant open any files,,cant open downloads or find them,,cant do anything on this. i dont know how or where to look,,terminal. /what the f is that,,how do you work it,,i checked on how to work this. just god dam crap,,you have to go to a college for hackers to know what all this shit is to work your browser,l. who ever made this for the common people. LIED,LIED. this is not for peopole,,its for hackers,,i tried to load windows on it,,it dont even let the software load,,i gues i9 have to delete this shit and then download,,this is shit,,i cant open a zip file,,i go to terminal and dont know what the fuck in doing in terminal. i check and forum say to put in different signalas or symbols i never seen before,,screw this and the dog it road in on. you ubuntu people are a bunch of crooks wanting to charge free for this. yes free is way to much money for this.

The cake is a lie.

The article on the other hand is great. Might use the addition of the most commonly used parameters.
Anyway, thanks. I was like “more” (mooar) 🙂 but forgot that you’re often satisfied with “less”

Hi
thanks a lot

Very useful and handy command to open and view files on Ubuntu desktop. thank you very much

Источник

Команда file в Linux

Команда file — одна из самых полезных, поскольку позволяет узнать тип данных, которые на самом деле содержатся внутри документа. Если у вас есть какой-либо файл, взятый из ненадёжного источника, не поленитесь проверить его с помощью этой команды, прежде чем нажать кнопку Открыть. Возможно, такая предосторожность покажется лишней, но она оградит вас от «встречи» с нежелательным контентом.

В большинстве дистрибутивов Linux утилита file (работу которой и запускает одноимённая команда) входит в стандартный набор программного обеспечения.

Синтаксис и опции file

Синтаксис команды file достаточно простой. Записывать её в эмуляторе терминала или консоли следует так:

file опции название_документа

Что же касается опций, то их у этой команды несколько десятков. Мы рассмотрим лишь основные:

  • -b, —brief — запрет на демонстрацию имен и адресов файлов в выводе команды;
  • -i, —mime — определение MIME-типа документа по его заголовку;
  • —mime-type, —mime-encoding — определение конкретного элемента MIME;
  • -f, —files-from — анализ документов, адреса которых указаны в простом текстовом файле;
  • -l, —list — список паттернов и их длина;
  • -s, —special-files — предотвращение проблем, которые могут возникнуть при чтении утилитой специальных файлов;
  • -P — анализ определенной части файла, которая обозначается различными параметрами;
  • -r, —raw — отказ от вывода /ooo вместо непечатных символов;
  • -z — анализ содержимого сжатых документов.

Для того, чтобы ознакомиться с полным списком опций, выполните в терминале команду:

Примеры использования file

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

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

file /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file2.tiff

Как видно на примере, картинки с расширениями gif и tiff в действительности оказались текстовыми документами, а архив с расширением zip — PDF документом. Кстати, команда file даёт возможность не только проверить, является ли архив архивом, но и заглянуть внутрь, чтобы узнать, что в нём содержится. Для этой цели используется опция -z:

file -z /home/main-user/losst/testarchive.zip

Как вы успели заметить, команда, возвращая ответ, постоянно выводит названия файлов, что в некоторых случаях бывает удобно, но зачастую только усложняет чтение результатов. Отключить эту функцию легко — воспользуйтесь опцией -b:

file -b /home/main-user/losst/test-file.gif /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file2.tiff

Иногда нужно узнать не просто тип файла, а его MIME-тип. В таком случае на помощь приходит опция -i:

file -i -b /home/main-user/losst/fileA.sbin /home/main-user/losst/fileG.aspx /home/main-user/losst/fileH.lua

Нередко по каким-либо причинам утилита не может найти указанный файл: например, вы ошиблись буквой в его названии или неверно указали папку, в которой он находится. Тогда вывод информации об этом файле предваряет фраза cannot open. Впрочем, есть возможность видоизменить результат, добавив в него сообщение об ошибке. Для этого используйте опцию -E.

Сравните вывод команды с опцией -E и без неё:

file -E -b /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file4.raw /home/main-user/losst/test-file.gif

file -b /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file4.raw /home/main-user/losst/test-file.gif

Еще один способ работы с утилитой file — запись названий и адресов документов в простой текстовый файл. Применяя этот способ на практике, не забывайте добавлять к команде опцию —files-from, после которой указывайте имя файла, содержащего список документов, и путь к нему.

file —files-from /home/main-user/losst/list_of_files.txt

Выводы

Команда file помогает избежать ситуаций, когда вам приходится открывать подозрительные файлы, не будучи уверенными в их содержимом. Также вы можете использовать её для проверки содержимого нескольких архивов, если есть необходимость найти потерявшийся в большом массиве файлов документ, но нет желания просматривать все архивы вручную.

Источник

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.

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.

Источник

Читайте также:  Windows 10 не синхронизирует время автоматически
Оцените статью