- Как открыть файл в терминале Linux
- Команды cat и tac
- Команды head и tail
- Команды more и less
- Команда most
- Текстовый редактор Nano
- How to open, create, edit, and view a file in Linux
- GUI text editors
- NEdit
- Geany
- Gedit
- Terminal-based text editors
- emacs
- Redirecting command output into a text file
- Creating an empty file with the touch command
- Redirecting text into a file
- Redirecting to the end of a file
Как открыть файл в терминале Linux
В Linux все настройки программ и самой операционной системы хранятся в текстовых документах. Также в текстовых документах сохраняются логи и другие необходимые данные. Поэтому при работе с Linux постоянно приходится просматривать и редактировать подобные текстовые и конфигурационные файлы.
В данной инструкции мы расскажем о том, как открыть файл в терминале Linux и какие команды для этого можно использовать. Материал будет актуален для любого дистрибутива Linux, включая Ubuntu, Debian, Kali Linux, CentOS и т.д.
Команды cat и tac
Если вам нужно открыть файл в терминале Linux, то для этого предусмотрено множество простых и эффективных способов. Пожалуй, самая часто используемая команда такого рода – это команда « cat ».
Чтобы использовать ее просто введите « cat » и название файла. Например, если вам нужно просмотреть содержимое файла « file_name.txt », то команда должна выглядеть вот так:
После выполнение данной команды все содержимое указанного файла будет выведено в терминал Linux. Данный способ вывода удобен для быстрого просмотра небольших файлов.
При использовании команды « cat » может понадобиться нумерация строк. В этом случае команду нужно вводить с параметром « -n ».
Также есть команда « tac », которая открывает файлы точно также как « cat », но выводит строки в обратном порядке (начиная с конца).
Обратите внимание , для того чтобы узнать больше о « cat » и « tac », а также других командах Linux, введите в терминал « man » (от англ. manual) и через пробел название интересующей вас команды, например, « man tac ». Это выведет подробную информацию о команде и список всех поддерживаемых параметров.
Команды head и tail
Если нужно открыть в терминале Linux большой файл, то вместо команды « cat » можно использовать « head » или « tail ». Данные команды выводят в терминал только часть файла. В случае « head » выводится только начало документа, а в случае « tail » только конец.
Чтобы открыть файл с помощью данной команды просто введите « head » или « tail » и название файла:
По умолчанию команды « head » и « tail » выводят по 10 строк с начала или конца файла. Но, при необходимости это значение можно изменить при помощи параметра « -n ». Для этого вводим « -n » и число строк (не отделяя пробелом). Выглядит это примерно так:
Кроме этого, вы можете ограничить количество информации, которую выводят команды « head » и « tail », указав значение в байтах. Для этого нужно использовать параметр « -c ». Например, чтобы вывести 100 байт нужно добавить параметр « -c » и указать значение 100 (не отделяя пробелом). Выглядит это примерно так:
Команды « head » и « tail » имеют общий набор параметров, но у « tail » есть уникальный параметр « -f », которого нет у « head ». При вызове « tail -f file_name.txt » выводимая информация будет автоматически обновляться. Это может быть удобно для наблюдения за логами.
Команды more и less
Для открытия больших файлов в терминале Linux можно использовать команды « more » и « less ». Команда « more » открывает файл в терминале Linux и позволяет пролистывать его только вниз при помощи клавиш Enter (одна строка вниз) и Space (страница вниз). Пролистывания вверх нет, поэтому, если вы случайно проскочили нужное вам место в файле, то вернуться назад не получится.
Чтобы открыть файл в терминале Linux с помощью команды « more » и « less » нужно ввести следующее:
Команда « less » также позволяет открывать большие файлы в терминале Linux, но она уже предоставляет больше возможностей. С помощью « less » можно пролистывать содержимое документа как вниз ( Page Down ), так и вверх ( Page Up ), переходить в конец ( End ) и начало файла ( Home ), пролистывать текст по одной строке ( Enter ), а также выполнять поиск в обоих направлениях.
Для того чтобы выполнить поиск после выполнения « less » нужно ввести слеш ( / ) и любой кусок текста. Чтобы перейти к следующему найденному отрывку нужно нажать N , а Shift-N возвращает к предыдущему найденному отрывку. Для поиска в обратном направлении вместо знака слеш ( / ) нужно вводить знак вопроса ( ? ) и после этого любой текст.
Учитывая большие возможности команды « less », для открытия файлов в терминале Linux в основном используют именно ее, а не команду « more ».
Команда most
Если возможностей « less » не хватает, то можно использовать команду « most ». Она предоставляет еще больше возможностей для открытия файлов в терминале Linux, но она может быть не установлена по умолчанию.
Если вы используете Ubuntu Linux , то для установки « most » нужно выполнить вот такую команду:
Команда « most » позволяет открывать сразу несколько файлов и переключаться между ними при необходимости. Также « most » позволяет редактировать текущий файл, переходить к нужной строке файла, разделять экран пополам, блокировать или пролистывать оба экрана одновременно и многое другое. По умолчанию, « most » не обертывает длинные строки, а использует горизонтальную прокрутку.
Для того чтобы открыть файл в терминале Linux с помощью « most » нужно выполнить вот такую команду:
Для перемещения по открытому файлу в «most» можно использовать стрелки на клавиатуре, Tab (вправо), Enter (вниз), T (начало), B (конец), J и G (переход к n-й строке), SPACE и D (один экран вниз), DELETE и U (один экран вверх). Для поиска вперед S , f или слеш , для поиска назад знак вопроса (?).
Текстовый редактор Nano
Если вам нужно не просто открыть файл в терминале Linux, но и отредактировать его, то лучше всего использовать не « most », а какой-нибудь более продвинутый текстовый редактор для терминала. Например, это может быть редактор Nano .
В Ubuntu Linux текстовый редактор Nano установлен по умолчанию, но если его нет в вашей системе, то вы можете его установить следующими командами:
Для CentOS, Fedora :
Для Debian, Ubuntu :
Чтобы открыть файл в терминале Linux при помощи редактора 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 – проверить орфографию;
Источник
How to open, create, edit, and view a file in Linux
One thing GNU/Linux does as well as any other operating system is give you the tools you need to create and edit text files. Ask ten Linux users to name their favorite text editor, and you might get ten different answers. On this page, we cover a few of the many text editors available for Linux.
GUI text editors
This section discusses text editing applications for the Linux windowing system, X Windows, more commonly known as X11 or X.
If you are coming from Microsoft Windows, you are no doubt familiar with the classic Windows text editor, Notepad. Linux offers many similar programs, including NEdit, gedit, and geany. Each of these programs are free software, and they each provide roughly the same functionality. It’s up to you to decide which one feels best and has the best interface for you. All three of these programs support syntax highlighting, which helps with editing source code or documents written in a markup language such as HTML or CSS.
NEdit
NEdit, which is short for the Nirvana Editor, is a straightforward text editor that is very similar to Notepad. It uses a Motif-style interface.
The NEdit homepage is located at https://sourceforge.net/projects/nedit/. If you are on a Debian or Ubuntu system, you can install NEdit with the following command:
For more information, see our NEdit information page.
Geany
Geany is a text editor that is a lot like Notepad++ for Windows. It provides a tabbed interface for working with multiple open files at once and has nifty features like displaying line numbers in the margin. It uses the GTK+ interface toolkit.
The Geany homepage is located at http://www.geany.org/. On Debian and Ubuntu systems, you can install Geany by running the command:
Gedit
Gedit is the default text editor of the GNOME desktop environment. It’s a great, text editor that can be used on about any Linux system.
The Gedit homepage is located at https://wiki.gnome.org/Apps/Gedit. On Debian and Ubuntu systems, Gedit can be installed by running the following command:
Terminal-based text editors
If you are working from the Linux command line interface and you need a text editor, you have many options. Here are some of the most popular:
pico started out as the editor built into the text-based e-mail program pine, and it was eventually packaged as a stand-alone program for editing text files. («pico» is a scientific prefix for very small things.)
The modern version of pine is called alpine, but pico is still called pico. You can find more information about how to use it in our pico command documentation.
On Debian and Ubuntu Linux systems, you can install pico using the command:
nano is the GNU version of pico and is essentially the same program under a different name.
On Debian and Ubuntu Linux systems, nano can be installed with the command:
vim, which stands for «vi improved,» is a text editor used by millions of computing professionals all over the world. Its controls are a little confusing at first, but once you get the hang of them, vim makes executing complex editing tasks fast and easy. For more information, see our in-depth vim guide.
On Debian and Ubuntu Linux systems, vim can be installed using the command:
emacs
emacs is a complex, highly customizable text editor with a built-in interpreter for the Lisp programming language. It is used religiously by some computer programmers, especially those who write computer programs in Lisp dialects such as Scheme. For more information, see our emacs information page.
On Debian and Ubuntu Linux systems, emacs can be installed using the command:
Redirecting command output into a text file
When at the Linux command line, you sometimes want to create or make changes to a text file without actually running a text editor. Here are some commands you might find useful.
Creating an empty file with the touch command
To create an empty file, it’s common to use the command touch. The touch command updates the atime and mtime attributes of a file as if the contents of the file had been changed — without actually changing anything. If you touch a file that doesn’t exist, the system creates the file without putting any data inside.
For instance, the command:
The above command creates a new, empty file called myfile.txt if that file does not already exist.
Redirecting text into a file
Sometimes you need to stick the output of a command into a file. To accomplish this quickly and easily, you can use the > symbol to redirect the output to a file.
For instance, the echo command is used to «echo» text as output. By default, this goes to the standard output — the screen. So the command:
The above command prints that text on your screen and return you to the command prompt. However, you can use > to redirect this output to a file. For instance:
The above command puts the text «Example text» into the file myfile.txt. If myfile.txt does not exist, it is created. If it already exists, its contents will be overwritten, destroying the previous contents and replacing them.
Be careful when redirecting output to a file using >. It will overwrite the previous contents of the file if it already exists. There is no undo for this operation, so make sure you want to completely replace the file’s contents before you run the command.
Here’s an example using another command:
The above command executes ls with the -l option, which gives a detailed list of files in the current directory. The > operator redirects the output to the file directory.txt, instead of printing it to the screen. If directory.txt does not exist, it is created first. If it already exists, its contents will be replaced.
Redirecting to the end of a file
The redirect operator >> is similar to >, but instead of overwriting the file contents, it appends the new data to the end of the file. For instance, the command:
Источник