Open file in console linux

Как открыть файл в терминале Linux

В Linux все настройки программ и самой операционной системы хранятся в текстовых документах. Также в текстовых документах сохраняются логи и другие необходимые данные. Поэтому при работе с Linux постоянно приходится просматривать и редактировать подобные текстовые и конфигурационные файлы.

В данной инструкции мы расскажем о том, как открыть файл в терминале Linux и какие команды для этого можно использовать. Материал будет актуален для любого дистрибутива Linux, включая Ubuntu, Debian, Kali Linux, CentOS и т.д.

Команды cat и tac

Если вам нужно открыть файл в терминале Linux, то для этого предусмотрено множество простых и эффективных способов. Пожалуй, самая часто используемая команда такого рода – это команда « cat ».

Чтобы использовать ее просто введите « cat » и название файла. Например, если вам нужно просмотреть содержимое файла « file_name.txt », то команда должна выглядеть вот так:

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

команда cat

При использовании команды « cat » может понадобиться нумерация строк. В этом случае команду нужно вводить с параметром « -n ».

команда cat

Также есть команда « tac », которая открывает файлы точно также как « cat », но выводит строки в обратном порядке (начиная с конца).

команда tac

Обратите внимание , для того чтобы узнать больше о « cat » и « tac », а также других командах Linux, введите в терминал « man » (от англ. manual) и через пробел название интересующей вас команды, например, « man tac ». Это выведет подробную информацию о команде и список всех поддерживаемых параметров.

Команды head и tail

Если нужно открыть в терминале Linux большой файл, то вместо команды « cat » можно использовать « head » или « tail ». Данные команды выводят в терминал только часть файла. В случае « head » выводится только начало документа, а в случае « tail » только конец.

Чтобы открыть файл с помощью данной команды просто введите « head » или « tail » и название файла:

head file_name.txt tail file_name.txt

команда head

По умолчанию команды « head » и « tail » выводят по 10 строк с начала или конца файла. Но, при необходимости это значение можно изменить при помощи параметра « -n ». Для этого вводим « -n » и число строк (не отделяя пробелом). Выглядит это примерно так:

head -n3 file_name.txt tail -n5 file_name.txt

команда head

Кроме этого, вы можете ограничить количество информации, которую выводят команды « head » и « tail », указав значение в байтах. Для этого нужно использовать параметр « -c ». Например, чтобы вывести 100 байт нужно добавить параметр « -c » и указать значение 100 (не отделяя пробелом). Выглядит это примерно так:

head -c100 file_name.txt tail -c200 file_name.txt

команда tail

Команды « head » и « tail » имеют общий набор параметров, но у « tail » есть уникальный параметр « -f », которого нет у « head ». При вызове « tail -f file_name.txt » выводимая информация будет автоматически обновляться. Это может быть удобно для наблюдения за логами.

Читайте также:  Arch linux ssh key

Команды more и less

Для открытия больших файлов в терминале Linux можно использовать команды « more » и « less ». Команда « more » открывает файл в терминале Linux и позволяет пролистывать его только вниз при помощи клавиш Enter (одна строка вниз) и Space (страница вниз). Пролистывания вверх нет, поэтому, если вы случайно проскочили нужное вам место в файле, то вернуться назад не получится.

Чтобы открыть файл в терминале Linux с помощью команды « more » и « less » нужно ввести следующее:

more file_name.txt less file_name.txt

команда more

Команда « less » также позволяет открывать большие файлы в терминале Linux, но она уже предоставляет больше возможностей. С помощью « less » можно пролистывать содержимое документа как вниз ( Page Down ), так и вверх ( Page Up ), переходить в конец ( End ) и начало файла ( Home ), пролистывать текст по одной строке ( Enter ), а также выполнять поиск в обоих направлениях.

Для того чтобы выполнить поиск после выполнения « less » нужно ввести слеш ( / ) и любой кусок текста. Чтобы перейти к следующему найденному отрывку нужно нажать N , а Shift-N возвращает к предыдущему найденному отрывку. Для поиска в обратном направлении вместо знака слеш ( / ) нужно вводить знак вопроса ( ? ) и после этого любой текст.

команда less

Учитывая большие возможности команды « less », для открытия файлов в терминале Linux в основном используют именно ее, а не команду « more ».

Команда most

Если возможностей « less » не хватает, то можно использовать команду « most ». Она предоставляет еще больше возможностей для открытия файлов в терминале Linux, но она может быть не установлена по умолчанию.

Если вы используете Ubuntu Linux , то для установки « most » нужно выполнить вот такую команду:

Команда « most » позволяет открывать сразу несколько файлов и переключаться между ними при необходимости. Также « most » позволяет редактировать текущий файл, переходить к нужной строке файла, разделять экран пополам, блокировать или пролистывать оба экрана одновременно и многое другое. По умолчанию, « most » не обертывает длинные строки, а использует горизонтальную прокрутку.

Для того чтобы открыть файл в терминале Linux с помощью « most » нужно выполнить вот такую команду:

команда most

Для перемещения по открытому файлу в «most» можно использовать стрелки на клавиатуре, Tab (вправо), Enter (вниз), T (начало), B (конец), J и G (переход к n-й строке), SPACE и D (один экран вниз), DELETE и U (один экран вверх). Для поиска вперед S , f или слеш , для поиска назад знак вопроса (?).

Текстовый редактор Nano

Если вам нужно не просто открыть файл в терминале Linux, но и отредактировать его, то лучше всего использовать не « most », а какой-нибудь более продвинутый текстовый редактор для терминала. Например, это может быть редактор Nano .

В Ubuntu Linux текстовый редактор Nano установлен по умолчанию, но если его нет в вашей системе, то вы можете его установить следующими командами:

Чтобы открыть файл в терминале Linux при помощи редактора Nano нужно выполнить следующую команду:

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

программа Nano

Для управления текстовым редактором Nano используются следующие комбинации клавиш:

  • Ctrl-G или F1 – просмотр справки;
  • Ctrl-X или F2 – выход из программы;
  • Ctrl-O или F3 – сохранение открытого файла;
  • Ctrl-J или F4 – выровнять текущий абзац;
  • Ctrl-R или F5 – загрузить содержимое другого файла в текущий;
  • Ctrl-W или F6 – выполнить поиск;
  • Ctrl-Y или F7 – пролистать страницу вперед;
  • Ctrl-V или F8 – пролистать страницу назад;
  • Ctrl-K или F9 – вырезать строку и запомнить;
  • Ctrl-U или F10 – вставить;
  • Ctrl-C или F11 – положение курсора;
  • Ctrl-T или F12 – проверить орфографию;
Читайте также:  Linux имена файлов команды

Источник

How to open the file in bash

The file is used to store the data permanently and use the data in any script when requires. A file can be opened for reading, writing, or appending. Many bash commands exist to open a file for reading or writing, such as `cat`, `less`, `more` etc. Any text editor can be used to open a file in bash. nano, vim, vi, etc., an editor is used to open a file from the terminal. Many GUI editors also exist in Linux to open a file, such as Gedit, Geany, etc. The file can be opened for reading or writing by using bash script also. The ways to open a file for various purposes have been shown in this tutorial.

Open file using Bash commands:

The uses of shell commands to open a file for creating or reading are shown in this tutorial. The uses of `cat`, `less`, and `more` commands have shown here.

Use of `cat` command:

The `cat` is a very useful command of bash to create or display the file’s content. Any file type can be created easily and quickly by opening the file using the `cat` command with the ‘>’ symbol. Run the following `cat` command to open a file named file1.txt for writing. If the filename already exists, then the previous content of the file will be overwritten by the new content; otherwise, a new file will be created.

Add the following content to the file.

A bash script is a command-line interpreted language.
Many automated tasks can be done easily using a bash script.

Press Ctrl+D to finish the writing task. The following output will appear after creating the file.

Now, run the following `cat` command to open the file.txt file for reading.

The following output will appear after executing the above command.

Use of `less` command:

The `less` command is used to open a file for reading only. It is mainly used to read the content of the large file. The user can move backward or forward through the file by using this command. It works faster than other text editors.

Run the following command to open the file1.txt file for reading. Here, the content of the file is very small. So when the user presses the enter key, then the content will go upward. Press the character ‘q’ to return to the command prompt.

The following output will appear after opening the file using the `less` command and pressing the enter key.

Use of `more` command:

Like the `less` command, the `more` command is used to open a large file for reading only. This command is mainly used to read a file’s large content in multiple pages to help the readers read long files.

Run the following command to open the file1.txt file for reading by using the `more` command. It is a small file. So all content of the file has displayed on one page.

The following output will appear after opening the file using the `more` command.

Open file using command-line editors:

The uses of vi and nano command-line editors for opening the file to create and read have been shown in this part of this tutorial.

Читайте также:  Линукс минт для компьютера

Use of vi editors:

One of the popular text editors of Linux is vi editors. It is installed on Ubuntu by default. The user can easily create, edit, and view any file by using this text editor. The advanced version of vi editors is called vim editor, which is not installed by default. This part of the tutorial shows how to use vi editor to open a file for creating and reading. Run the following command to open the file2.txt file for writing.

You have to press the character ‘i’ to start writing into the vi editor. Add the following content to the file.

Writing a file using vi editors.

You can do any of the following tasks after writing the content of the file.

  1. Type :wq to quit the editor after saving the file.
  2. Type :w to keep the file open in the editor after saving.
  3. Type :q to quit the editor without saving the file.

The following output shows that ‘:wq’ has been typed to quit the editor after saving the file.

Run the following command to open the file2.txt file and check the content exists or not that was added in the file.

The following output shows that the file contains the data that was added before. Here,’:’ has typed to quit the editor.

Use of nano editor:

Another useful and popular editor of Linux is the nano editor that is used to open a file for writing and reading. It is easier to use than the vi editor and more user-friendly than other command-line editors. Run the following command to open the file3.txt file for writing using nano editor.

Add the following content to the file.

Writing a file using nano editor.

If you type Ctrl+X after adding the content to the file, it will ask you to save the file. The following output will appear if you press the character, ‘y’. Now, press the enter to quit the editor after saving the file.

Open file using GUI text editor:

The ways to use gedit and geany GUI-based text editor have shown in the part of this tutorial.

Use of gedit editor:

The gedit is mostly used GUI-based text editor that is installed by default on maximum Linux distributions. Multiple files can be opened by using this editor. Run the following command the open the existing file1.txt file using gedit editor.

The following output will appear after executing the command.

Use of geany editor:

Geany is a more powerful GUI-based editor than the gedit editor, and you have to install it to use it. It can be used to write code for many types of programming languages. Run the following command to install the geany editor.

After installing the editor, run the following command to open the file1.txt file.

The following output will appear after executing the command.

Conclusion:

Many ways to open a file for reading or writing have been shown in this tutorial by using bash command, command-line editors, and GUI-based editors. The Linux users can select any of the ways mention here to open a file in bash.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

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