- 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
- Выводы
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:
Источник
Как открыть текстовый файл в Linux
В Linux все настройки, все логи, и почти вся информация хранится в обычных текстовых файлах. Важно уметь правильно и эффективно посмотреть содержимое файла linux с помощью терминала. Это еще одна из статей, ориентированных на новичков.
Вот вы скажете, а что их там открывать, открыл и посмотрел или изменил, и все. Да, но не совсем, терминал Linux настолько гибкий инструмент, что даже обычный просмотр файлов можно очень сильно оптимизировать. Просмотр содержимого файлов Linux — это тоже искусство. В этой инструкции мы рассмотрим все команды, с помощью которых можно открыть текстовый файл linux, поговорим о том как ими пользоваться, а также приведем несколько примеров.
Просмотр файла в Linux полностью
Самая простая и в то же время наиболее часто используемая утилита для просмотра содержимого файла в Linux это cat. Выводит все содержимое файла в стандартный вывод. В параметре нужно передать только адрес файла, или нескольких файлов. Идеально подходит для просмотра небольших файлов. Общий синтаксис команды cat такой:
$ cat опции адрес_файла .
Например просмотр содержимого файла linux /etc/passwd:
Также можно посмотреть сразу несколько файлов:
cat /etc/passwod /etc/group
Если файл доступен только для пользователя root, то нужно перед командой написать sudo:
sudo cat /etc/shadow
Опция -n включает нумерацию строк:
cat -n /var/log/Xorg.0.log
Для удобства, можно включить отображение в конце каждой строки символа $
cat -e /var/log/Xorg.0.log
А также отображение табуляций, все табуляции будут заменены на символ ^I:
cat -T /var/log/Xorg.0.log
Больше о ней говорить не будем, потому что большинство её опций направлены на форматирование вывода, более подробную информацию вы можете посмотреть в статье: Команда cat в Linux.
Просмотр файла в Linux с прокруткой
Если файл очень длинный и его содержимое не помещается на одном экране, cat использовать не очень удобно. для таких случаев есть less. Синтаксис тот же:
$ less опции файл
Также ее можно комбинировать с cat:
$ cat адрес_файла | less
Например, посмотрим лог Х сервера:
Теперь мы можем листать содержимое файла в Linux с помощью стрелок вверх-вниз. Для того чтобы выйти нажмите q. Также эта утилита поддерживает поиск. Для поиска по файлу нажмите слеш «/». О более правильном способе поиска мы поговорим дальше.
Просмотр только начала или конца файла
Очень часто нам не нужен файл целиком. Например, достаточно посмотреть несколько последних строчек лога, чтобы понять суть ошибки, или нужно увидеть только начало конфигурационного файла. Для таких случаев тоже есть команды. Это head и tail (голова и хвост).
По умолчанию head открывает текстовый файл в Linux и показывает только десять первых строчек переданного в параметре файла:
Можно открыть сразу два текстовых файла в Linux одновременно аналогично cat:
head /etc/passwd /etc/group
Так можно открыть текстовый файл linux или несколько и вывести по десять первых строчек каждого из них.
Если вам не нужны все 10 строчек, опцией -n и цифрой можно указать количество строк которые нужно вывести. Например, 5:
head -n5 /var/log/apt/history.log
Тот же результат можно получить опустив букву n и просто передав цифру в качестве ключа:
head -5 /var/log/apt/history.log
Также можно задать количество байт, которые нужно вывести с помощью опции -с и числа. Например: 45:
head -c45 /var/log/apt/history.log
Тоже хотите подсчитать действительно ли там 45 символов? Используйте команду wc:
head -c45 /var/log/emerge.log | wc -c
Команда tail наоборот, выводит 10 последних строк из файла:
Утилита tail тоже поддерживает изменение количества строк, с помощью опции -n. Но она обладает еще одной интересной и очень полезной опцией -f. Она позволяет постоянно обновлять содержимое файла и, таким образом, видеть все изменения сразу, а не постоянно закрывать и открывать файл. Очень удобно для просмотра логов linux в реальном времени:
tail -f /var/log/Xorg.0.log
Просмотр содержимого файла с поиском
В большинстве случаев нам нужен не полностью весь файл, а только несколько строк, с интересующей нас информацией. Можно выполнить просмотр файла linux предварительно отсеяв все лишнее с помощью grep. Сначала синтаксис:
$ grep опции шаблон файл
Или в комбинации с cat:
$ cat файл | grep опции шаблон
Например выведем из лога только предупреждения:
cat /var/log/Xorg.0.log | grep WW
Но это еще не все, многие не знают, но у этой утилиты еще несколько полезных опций.
С помощью опции -A можно вывести несколько строк после вхождения:
cat /var/log/Xorg.0.log | grep -A2 WW
С помощью -B — до вхождения:
cat /var/log/Xorg.0.log | grep -B2 WW
А опция -С позволяет вывести нужное количество строк до и после вхождения шаблона:
cat /var/log/Xorg.0.log | grep -C2 WW
Также с помощью grep можно подсчитать количество найденных строк:
cat /var/log/Xorg.0.log | grep -c WW
Шаблоном может быть строка и простые спецсимволы замены. Если вы хотите использовать регулярное выражение укажите опцию -e или используйте egrep. Многие спрашивают, а какая разница между этими утилитами — уже никакой, в большинстве дистрибутивов egrep это ссылка на grep -e. А теперь пример:
cat /var/log/Xorg.0.log | egrep ‘WW|EE’
В примерах этого раздела использовались символы перенаправления ввода, подробнее о них можно почитать в этой статье.
Просмотр файлов Linux в сжатом виде
Иногда можно встретить в системе текстовые файлы в сжатом виде, формате gz. Это, например, конфигурационный файл ядра, или логи некоторых программ. Для того чтобы открыть файл в linux через терминал не распаковывая его есть целый ряд аналогов вышеописанных утилит с приставкой z. Это zcat, zless, zgerp, zegrep.
Например, открываем сжатый файл для просмотра:
Или более практичный пример, распаковываем и копируем конфигурационный ядра в текущую директорию:
zcat /porc/cofig.gz .config
Так же можно использовать less, для просмотра сжатых файлов с прокруткой:
А для фильтрации сжатых файлов по шаблону есть zgrep и zegrep. Например, ищем в сжатом логе ошибки:
zgrep ‘EE’ /var/log/Xorg.log.gz
Редактирование файлов в Linux
Довольно часто, обычного просмотра файла недостаточно и в нём надо что-то поправить. Для решения этой задачи cat уже не подойдёт, надо использовать текстовый редактор. В терминале можно пользоваться nano или vim, а в графическом интерфейсе — gedit. Чтобы открыть файл в терминале выполните:
$ nano /путь/к/файлу
sudo nano /etc/default/grub
Для большинства файлов в директории /etc/ запись доступна только пользователю root. Поэтому команду надо выполнять от имени суперпользователя с помощью sudo. После нажатия клавиши Enter утилита запросит пароль. Введите его, несмотря на то, что символы пароля не отображаются, это нормально. После внесения изменений сохраните их с помощью сочетания клавиш Ctrl + O.
Аналогично, можно открыть этот же файл в текстовом редакторе:
sudo gedit /etc/default/grub
Открывать подобные файлы из файлового менеджера не надо, вы сможете их открыть для просмотра, но при попытке записать в них что-то получите ошибку, лучше пользоваться терминалом.
Выводы
Вот и все. Разобрал все достаточно подробно. Теперь вы точно знаете как правильно открыть файл в терминале Linux. Если остались еще вопросы, оставляйте комментарии.
Источник