- 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
- How to use sed to find and replace text in files in Linux / Unix shell
- Find and replace text within a file using sed command
- Syntax: sed find and replace text
- Examples that use sed to find and replace
- sed command problems
- How to use sed to match word and perform find and replace
- Recap and conclusion – Using sed to find and replace text in given files
- How to edit text files from the command line
- Using the Nano editor
- Using the Vim editor
- More Information
- Редактирование текста в Linux с помощью команд Vi, cat, less
- Редактор командной строки
- Сохранение и выход
- Другие способы просмотра файлов
- Навигация по файлу в Vi
- Удаление текста
- Отмена
- Вывод
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:
Источник
How to use sed to find and replace text in files in Linux / Unix shell
Find and replace text within a file using sed command
The procedure to change the text in files under Linux/Unix using sed:
- Use Stream EDitor (sed) as follows:
- sed -i ‘s/old-text/new-text/g’ input.txt
- The s is the substitute command of sed for find and replace
- It tells sed to find all occurrences of ‘old-text’ and replace with ‘new-text’ in a file named input.txt
- Verify that file has been updated:
- more input.txt
Let us see syntax and usage in details.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | sed utility on Linux, macOS or Unix-like OS |
Est. reading time | 4 minutes |
Syntax: sed find and replace text
The syntax is:
sed ‘s/word1/word2/g’ input.file
## *bsd/macos sed syntax#
sed ‘s/word1/word2/g’ input.file > output.file
sed -i ‘s/word1/word2/g’ input.file
sed -i -e ‘s/word1/word2/g’ -e ‘s/xx/yy/g’ input.file
## use + separator instead of / ##
sed -i ‘s+regex+new-text+g’ file.txt
The above replace all occurrences of characters in word1 in the pattern space with the corresponding characters from word2.
Examples that use sed to find and replace
Let us create a text file called hello.txt as follows:
$ cat hello.txt
The is a test file created by nixCrft for demo purpose.
foo is good.
Foo is nice.
I love FOO.
I am going to use s/ for substitute the found expression foo with bar as follows:
sed ‘s/foo/bar/g’ hello.txt
Sample outputs:
- 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 ➔
Please note that the BSD implementation of sed (FreeBSD/MacOS and co) does NOT support case-insensitive matching. You need to install gnu sed. Run the following command on Apple Mac OS:
$ brew install gnu-sed
######################################
### now use gsed command as follows ##
######################################
$ gsed -i ‘s/foo/bar/g I ‘ hello.txt
$ cat hello.txt
sed command problems
Consider the following text file:
$ cat input.txt
http:// is outdate.
Consider using https:// for all your needs.
Find word ‘http://’ and replace with ‘https://www.cyberciti.biz’:
sed ‘s/ http:// / https://www.cyberciti.biz /g’ input.txt
You will get an error that read as follows:
Our syntax is correct but the / delimiter character is also part of word1 and word2 in above example. Sed command allows you to change the delimiter / to something else. So I am going to use +:
sed ‘s+ http:// + https://www.cyberciti.biz +g’ input.txt
Sample outputs:
How to use sed to match word and perform find and replace
In this example only find word ‘love’ and replace it with ‘sick’ if line content a specific string such as FOO:
sed -i -e ‘/FOO/s/love/sick/’ input.txt
Use cat command to verify new changes:
cat input.txt
Recap and conclusion – Using sed to find and replace text in given files
The general syntax is as follows:
## find word1 and replace with word2 using sed ##
sed -i ‘s/word1/word2/g’ input
## you can change the delimiter to keep syntax simple ##
sed -i ‘s+word1+word2+g’ input
sed -i ‘s_word1_word2_g’ input
## you can add I option to GNU sed to case insensitive search ##
sed -i ‘s/word1/word2/gI’ input
sed -i ‘s_word1_word2_gI’ input
See BSD(used on macOS too) sed or GNU sed man page by typing the following command:
man sed
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to edit text files from the command line
Although you can edit text files in cPanel (if your account includes cPanel), it is often quicker and easier to do so from the command line. This article describes how to use the Nano and Vim editors to edit text files from the command line.
The Nano editor is probably easier for beginners to use initially. On the other hand, the Vim editor is in more widespread use, and has a long list of features. Try both editors, and use whichever one you feel more comfortable with.
Using the Nano editor
Editing files with the Nano text editor is easy. To open a file in Nano, type the following command at the command line:
Replace filename with the name of the file that you want to edit.
To edit the file, just start typing your changes. To navigate around the file, you can use the arrow keys on your keyboard. If the file’s contents are too long to fit on the screen, you can press Ctrl+V to move forward a page, and Ctrl+Y to move back a page.
When you are ready to save your changes, press Ctrl+O, verify the filename, and then press ENTER. To exit Nano, press Ctrl+X.
You can access Nano’s online help at any time by pressing Ctrl-G.
Using the Vim editor
To open a file for editing in Vim, type the following command at the command line:
Editing files with Vim is not as intuitive as with Nano. You can’t just start typing your changes, because Vim starts in normal mode. In normal mode, anything you type on the keyboard is interpreted as a potential command, not changes to the text.
To make changes to the text, you must enter insert mode. To do this, type i . Note that the status line at the bottom of the screen changes to —INSERT— . You can now make changes to the file. To navigate around the file while you are in insert mode, use the arrow keys and Page Up/Page Down keys.
To return to normal mode, press ESC. Note that the —INSERT— status line at the bottom of the screen goes blank. Now you can type commands to save your changes, search for text, and so on.
To write your changes without exiting Vim, type :w and then press ENTER. To exit Vim, type :q and then press ENTER. To write your changes and exit Vim at the same time, type :wq and then press ENTER.
More Information
This article is a very basic introduction to using the Nano and Vim text editors. Both of these editors, and Vim in particular, have many more features and customizations available:
Источник
Редактирование текста в Linux с помощью команд Vi, cat, less
Vi — очень мощный инструмент. В статье сделан упор не на возможностях редактора, а научить его основам.
Редактор командной строки
Vi — текстовый редактор командной строки. Командная строка — это совершенно другая среда для вашего графического интерфейса. Это одно окно с вводом и выводом текста. Vi был спроектирован для работы с этими ограничениями и в результате он достаточно мощный. Vi предназначен для работы в качестве простого текстового редактора. Однако он обладает гораздо большей мощностью по сравнению с Notepad или Textedit.
В итоге, вы должны забыть про мышь. Все в Vi делается через клавиатуру.
В Vi есть два режима. Режим вставки и режим редактирования. В режиме ввода вы можете вводить содержимое в файл. В режиме редактирования вы можете перемещаться по файлу, выполняя следующие действия:
Перечислим основные распространенные ошибки. Во-первых, начинать вводить команды, не возвращаясь в режим редактирования. Во — вторых, вводить ввод без предварительной вставки.
Когда мы запускаем vi, мы обычно выдаем его с одним аргументом командной строки. Он же является файлом для редактирования.
vi
Если вы забыли указать файл, есть способ открыть его в vi. Когда мы указываем файл, он может иметь абсолютный или относительный путь.
Отредактируем наш первый файл.
Когда вы запускаете эту команду, она открывает файл. Если файл не существует, он создаст его для вас, а затем откройте его. После ввода vi это будет выглядеть примерно так.
Вы всегда начинаете в режиме редактирования, поэтому первое, что мы собираемся сделать, это переключиться в режим вставки, нажав i
Теперь введите несколько строк текста и нажмите клавишу Esc, и вы вернетесь в режим редактирования.
Сохранение и выход
Есть несколько способов сделать данный маневр. Для начала убедитесь, что вы находитесь в режиме редактирования.
Если вы не уверены, находитесь ли вы в режиме редактирования можно посмотреть в нижнем левом углу. В качестве альтернативы вы можете просто нажать Esc, чтобы быть уверенным. Если вы уже находитесь в режиме редактирования, нажатие клавиши « Esc» ничего не делает, поэтому вы не причините вреда.
- ZZ — Сохранить и выйти
- :q! — отменить все изменения, начиная с последнего сохранения, и выйти
- : w — сохранить файл, но не выходить
- : wq — снова сохранить и выйти
Большинство команд в vi выполняются, как только вы нажимаете последовательность клавиш. Любая команда, начинающаяся с двоеточия (:), требует, чтобы вы нажали для завершения команды.
Другие способы просмотра файлов
vi позволяет нам редактировать файлы. Кроме того, мы можем использовать его для просмотра файлов. Надо признать, есть две другие команды, которые немного более удобны для этой цели. Во-первых, cat, который на самом деле означает конкатенацию. Ее основная цель — объединить файлы, но в своей основной форме это полезно для просмотра файлов.
Запустив команду cat с одним аргументом командной строки, можно увидеть содержимое файла на экране, а затем появится подсказка.
Если вы случайно запустили cat без указания аргумента командной строки, вы заметите, что курсор перемещается на следующую строку, а затем ничего не происходит. Если вы наберете что-то, нажмите , вы увидите cat зеркально отразит ваш ввод на экране. Чтобы выйти отсюда, следует нажать + c, который является универсальным сигналом для отмены в Linux.
На самом деле, когда у вас возникают проблемы, вы обычно можете нажать + c, чтобы избежать неприятностей.
Эта команда хороша, когда у нас есть маленький файл для просмотра.
А если файл большой? Основная часть контента будет летать по экрану, и мы увидим только последнюю страницу контента. Для больших файлов лучше подходит команда, less.
less
less позволяет перемещаться вверх и вниз по файлу с помощью клавиш со стрелками. Вы можете перейти вперед на целую страницу с помощью пробела или назад на страницу, нажав b. При завершении, следует нажать q для выхода.
Навигация по файлу в Vi
Теперь вернемся к файлу, который мы только что создали, и введем еще немного контента. В режиме вставки вы можете использовать клавиши со стрелками для перемещения курсора. Введите еще два абзаца содержания, затем нажмите Esc, чтобы вернуться в режим редактирования.
Ниже приведены некоторые из множества команд, которые вы можете вводить для перемещения по файлу. Посмотрите как они работают.
- Клавиши со стрелками — перемещать курсор
- j, k, h, l — переместить курсор вниз, вверх, влево и вправо (аналогично клавишам со стрелками)
- ^ — переместить курсор в начало текущей строки
- $ — переместить курсор в конец текущей строки
- nG — перейти к n- й строке (например, 5G — к 5-й строке)
- G — перейти к последней строке
- w — перейти к началу следующего слова
- nw — переместиться вперед
- b — перейти к началу предыдущего слова
- nb — вернуться на n слово
- < — переместиться назад на один абзац
- > — перейти на один абзац вперед
Набрав set nu в режиме редактирования в vi, позволяет включить номера строк. В итоге, включение номеров строк делает работу с файлами намного проще.
Удаление текста
Если мы хотим перейти в vi, у нас будет довольно много вариантов. Некоторые из них также позволяют нам предшествовать им с числом, которое можно перемещать столько раз. Удаление работает аналогично перемещению. Всего несколько команд удаления позволяют нам включить команду перемещения, чтобы определить, что будет удалено.
Вот некоторые способы, которыми мы можем удалять текст в vi.
- x — удалить один символ
- nx — удалить n символов (например, 5x удаляет пять символов)
- dd — удалить текущую строку
- dn — d, сопровождаемый командой движения.
Отмена
Отменить изменения в vi довольно легко. Это символ u .
- u — отменить последнее действие (вы можете продолжать нажимать u, чтобы продолжить отмену)
- U (Заглавная) — отменить все изменения в текущей строке
Вывод
Теперь вы можете сделать основное редактирование в vi.
- скопировать и вставить
- поиск и замена
- буферы
- маркеры
- диапазоны
- настройки
Кроме того, в статье мы ознакомились со следующими командами:
- VI — редактировать файл
- cat — просмотр файла.
- less — удобство для просмотра больших файлов.
Источник