- A Beginner’s Guide on How to Use Nano Text Editor in Linux
- Install Nano Editor in Linux
- Nano Keyboard Shortcuts
- Create a New File in Nano
- Open a File in Nano
- Editing Files in Nano
- Search for Text in Nano
- Copy/Paste/Cut Text in Nano
- Save File in Nano
- Save File with Backup
- Exit Nano Editor
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- How to Save and Exit in Nano Editor? [A Beginner’s Guide]
- How to Save and Exit Nano Save Nano Command: Ctrl+O will save the modifications you’ve made to the file. When you save the file, it will be generated if it does not already exist. Exit Nano Command: Ctrl+X will close nano. If any patches haven’t been saved yet into your system, you’ll be prompted to do so.
- Some Useful Nano Editor Commands
- Conclusion
- Использование редактора nano
- Создать новый файл
- Открыть существующий файл для редактирования
- Сохранение изменений
- Сохранить и продолжить работу
- Сохранить и выйти
- Выход без сохранения изменений
- Копирование и вставка
- Копирование и вставка строк
- Копирование и вставка произвольного текста
- Поиск текста
- Поиск и замена текста
- Горячие клавиши
- Кое-что еще
- Ctrl = Esc Esc
- Только для чтения
- Резервная копия файла
A Beginner’s Guide on How to Use Nano Text Editor in Linux
Nano is a command line text editor, that comes preinstalled in almost every Linux distribution. It is often preferred by new users because of its simplicity, compared to other command line text editors such as vi/vim and emacs. It has plenty of useful features such as syntax coloring, line numbering, easy search and many others.
Install Nano Editor in Linux
If for any reason nano is not already installed on your Linux distro, you should be able to easily install it with the following commands:
Nano Keyboard Shortcuts
Nano uses keyboard combinations for different functions, such as to find text in a file, justify text etc. Those combinations are really easy and are visible while you edit your file. They change automatically depending on what action you are taking.
One thing you should know is that a keyboard shortcut represented with ^ and a symbol (for example ^W ) is a combination of the Ctrl key and that symbol (Ctrl+W in our example).
A combination that is shown to start with M means that it needs to be completed by pressing Alt key and the following symbol.
Below are listed the options that you will see when you first open nano:
- G Get Help
- ^O Write Out
- ^W Where Is
- ^K Cut Text
- ^J Justify
- ^C Cur Pos
- M-U Undo
- ^X Exit
- ^R Read File
- ^\ Replace
- ^U Uncut Text
- ^T To Spell
- ^_ Go To Line
- M-E Redo
You don’t need to remember each option as it is always in front of you. You can get the full list of keyboard combinations by pressing ^G (or press F1) which will open nano’s help menu. You will notice that some shortcuts can be used with single key.
For example F1 key to get help or F2 to exit nano.
Nano Editor Shortcut Keys
Create a New File in Nano
Creating new file is simple as running nano:
This will open the editor and upon saving the file, it will ask you to give it a name with which the new file will be saved.
Create New File in Nano
Open a File in Nano
To open a file you can run:
The above command will try to open the file “my_text_file.txt” from your home directory. If the file does not exist, nano will try to create it.
Sometimes, you may need to open a file and go at exact line or column. Nano allows you to do this with:
Will open your .bashrc file and the cursor will be located on the third line, second column.
Open File in Nano
Editing Files in Nano
Upon opening or creating files you can start editing/writing immediately. Unlike vim, there is no need to switch to edit mode in nano. To move the cursor around the file, you can use the arrow keys on your keyboard.
Edit Files in Nano
Search for Text in Nano
You can search for text inside a file by using ^W , which represents the “where is” option. This will open a search input above the menu, where you can input the text you are search for:
Search Text in Nano
You will also see that the bottom menu will change and will show some additional options. They are pretty much self explanatory, so we will review the more important ones.
- Search with regular expressions – press M-R (Alt + R keys) and input your search with the regular expressions you wish to use.
- Go to line – press ^T (Ctrl + T) followed by the line to which you want to move the cursor to.
- Replace text – press ^R (Ctrl +T) in search mode, or ^\ in regular mode. You will be asked to enter your search, after pressing Enter, you will be asked to input the text which will be used for the replacement. Finally you will be asked if you wish to replace a matched instance of your search, or all matches. If you choose “No”, the cursor will be moved towards the next match.
- Go to first line – press ^Y (Ctrl + Y).
- Go to last line – press ^V (Ctrl +V).
Copy/Paste/Cut Text in Nano
Nano’s interface is very similar to a GUI text editors. If you wish to copy or cut a text in GUI editor, you will first have to select it. Same thing goes in nano. To mark a text press Ctrl + ^ then move the cursors with the arrow keys.
- To copy the marked text press Alt + ^.
- To cut the marked text press ^K (Ctrl +K).
- To paste the marked text, move the cursor to a suitable position and press ^U (Ctrl + U).
Copy and Paste Text in Nano
Save File in Nano
If you wish to save your current changes to the file, press the ^O (Ctrl + O) combination. If you are editing a new file, you will be asked to give that file a name. This will save your current changes and nano will remain opened so you can continue making changes to the file.
Save File with Backup
Sometimes when editing a file, you may want to keep temporary copies of the same file just in case. You can use nano’s -B option, which will create backup of the file you are editing. You can use it in combination with the -C option to tell nano where to save those backups like this:
The above will make backup copies of the file myfile.txt in the folder “backups” located in the user’s home directory. Note that the backup directory should be existing, otherwise, nano will tell you that the directory is invalid.
Exit Nano Editor
To exit nano, simply press ^X (Ctrl +X keys). If the file has not been previously saved, you will be asked to save the changes with yes/no or cancel the exit.
Conclusion
Nano is an easy to use command line text editor, that attracts users with its simplicity. Its interface is similar to those of GUI editors which makes it perfect for Linux newcomers.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
How to Save and Exit in Nano Editor? [A Beginner’s Guide]
This tutorial is a guide for all the beginners who want to use save and exit commands in nano editor.
List of content you will read in this article:
Nano is the most fundamental, command-line-based text editor for Linux. It has all common text editor features, including highlighting syntaxes, multiple buffers, scanning and replacement with regular expression support, type corrections, and UTF-8 encoding. You can easily save and exit in the nano editor through the command-line options given in this tutorial.
How to Save and Exit Nano - Save Nano Command: Ctrl+O will save the modifications you’ve made to the file. When you save the file, it will be generated if it does not already exist.
- Exit Nano Command: Ctrl+X will close nano. If any patches haven’t been saved yet into your system, you’ll be prompted to do so.
You must have the write permissions on the file to save it. You must have written permission to the directory where the file would be generated while making a new file in the nano editor to save the file.
Some Useful Nano Editor Commands
Any command prefixed with a caret symbol (^) means to use the Ctrl key (e.g., ^G means to press the Ctrl+G keys at the same time).
Here we have listed the top nano editor command which you should know:
- ^G: nano help
- ^A: move to beginning of line in nano
- ^E: move to end of line in nano
- ^Y: move down a page — next page in nano
- ^V: move up a page — previous page in nano
- ^_: move to a specific line (^_^V moves to the top of the file, ^_^Y to the bottom)
- ^C: find out what line the cursor is currently on
- ^W: search or find some text in nano
- ^D: delete character currently under the cursor
- ^K: delete line in nano, nano remove line
- Also for remove or clear or delete some content or multiple lines you can select lines with your mouse and then use CTRL+K.
- ^O: save file nano (you will be prompted for a file to save to)
- ^X: exit nano (you will be prompted to save your file if you have not)
Conclusion
Using the command Ctrl+O and Ctrl+X, you can easily save nano file and exit a file in a nano editor. But be careful; you must have the write permission to do these for all the files and directories you are working on, and then only will you be able to make any changes in the nano editor. Hence in this way, we can save and exit in the nano editor using the command line.
Источник
Использование редактора nano
Редактор nano — это консольный текстовый редактор. Он есть почти во всех дистрибутивах Linux, есть в macOS и его можно запустить под Windows. nano часто используется для редактирования конфигурационных файлов, когда графический интерфейс отсутствует.
Управление в nano осуществляется с клавиатуры с использованием горячих клавиш. В нижней части редактора приведен список основных сочетаний клавиш. Символ ^ означает клавишу Ctrl . Например, ^X означает сочетание клавиш Ctrl+X . Регистр символов не учитывается, сочетание Ctrl+X эквивалентно Ctrl+x .
Рассмотрим, как выполнять основные действия при работе с nano.
Создать новый файл
Чтобы создать файл достаточно просто запустить редактор без параметров. Когда вы будете закрывать редактор, то необходимо будет ввести имя файла.
Также можно сразу задать имя нового файла:
После выполнения команды запустится редактор nano и в нем откроется для редактирования новый пустой файл.
Открыть существующий файл для редактирования
Чтобы отредактировать существующий файл, необходимо запустить редактор nano и указать путь до файла, который нужно открыть:
Сохранение изменений
Сохранить и продолжить работу
Вы отредактировали файл и хотите сохранить изменения, но не закрывать редактор. В таком случае используется сочетание клавиш:
Ctrl+O
В строке статуса появится сообщение: File Name to Write: имя_файла (если имя файла отсутствует, то нужно ввести имя файла). Для сохранения изменений нажмите Enter .
Сохранить и выйти
Чтобы сохранить изменения и выйти из редактора можно воспользоваться сочетанием клавиш:
Ctrl+X
В данном случае, если вы изменяли файл, то появится вопрос: «Save modified buffer (ANSWERING No Will DESTROY CHANGES)? «. Нажмите клавишу y . Появится вопрос на ввод имени файла. Введите новое имя файла или просто нажмите Enter . Изменения будут сохранены, редактор закроется.
Выход без сохранения изменений
Чтобы выйти из редактора и не сохранять изменения используется сочетание клавиш:
Ctrl+X
Есть появится вопрос «Save modified buffer . «, нажмите n .
Копирование и вставка
Копирование и вставка строк
Чтобы вырезать строку целиком и поместить ее в буфер, переместите курсор на требуемую строку и нажмите:
Ctrl+K
Чтобы вставить строку из буфера нажмите:
Ctrl+U
Копирование и вставка произвольного текста
Чтобы скопировать произвольный текст в буфер обмена, его необходимо сначала выделить. Чтобы начать выделение поместите курсор на начало текста, который планируется копировать, и нажмите:
Ctrl+6
Перемещайте курсор, текст будет выделяться.
Чтобы скопировать выделенный текст в буфер обмена, нажмите:
Alt+6
или, чтобы вырезать выделенный текст, нажмите:
Ctrl+K
Переместите курсор в то место, куда необходимо вставить текст из буфера. Чтобы вставить текст из буфера нажмите:
Ctrl+U
Поиск текста
Для поиска текста внутри файла используется сочетание клавиш:
Ctrl+W
Нужно ввести строку для поиска и нажать Enter .
Курсор будет помещен на первое вхождение искомого текста (относительно курсора). Чтобы перейти к следующему вхождению, нажмите:
Alt+W
Чтобы прекратить поиск, нажмите:
Ctrl+C
Поиск и замена текста
Чтобы найти и заменить текст используется сочетание клавиш:
Ctrl+\
Появится запрос на ввод текста для поиска. Введи строку для поиска и нажмите Enter .
Затем появится запрос на ввод текста, на который необходимо выполнить замену. Введите строку и нажмите Enter .
Далее будет выдан запрос на замену найденного вхождения искомой строки. Можно нажать клавишу A , чтобы заменить сразу все вхождения в файле или использовать клавиши Y или N , чтобы заменять или нет, найденные вхождения искомой строки.
Горячие клавиши
Чтобы вывести информацию по всем горячим клавишам, используется сочетание Ctrl+G .
Наиболее часто используемые горячие клавиши nano:
Горячие клавиши | Описание |
---|---|
Ctrl+A | Переместить курсор в начало строки. |
Ctrl+E | Переместить курсор в конец строки. |
Ctrl+Y | Переместить курсор на 1 страницу вверх (аналог PageUp ) |
Ctrl+V | Переместить курсор на 1 страницу вниз (аналог PageDown ) |
Ctrl+_ | Перейти к определенной строке (нужно будет ввести номер строки). |
Ctrl+C | Показать на какой строке и в какой позиции находится курсор. |
Ctrl+W | Поиск текста в файле. Необходимо ввести строку для поиска. |
Ctrl+\ | Поиск и замена текста в файле. Сначала вводится строка для поиска, затем строка для замены. |
Ctrl+D | Удалить символ под курсором. |
Ctrl+K | Удалить текущую строку. |
Ctrl+O | Сохранить изменения, не закрывая редактор. |
Ctrl+X | Выход из редактора. Если файл был изменен, появится запрос на сохранение изменений. |
Кое-что еще
Еще пара интересных трюков при работе с nano, о которых не все знают.
Ctrl = Esc Esc
Вместо клавиши Ctrl можно использовать двойное нажатие на клавишу Esc . Например,
Esc+Esc+X
Это эквивалентно сочетанию Ctrl+X .
Только для чтения
Чтобы открыть файл только для чтения используется ключ -v :
Резервная копия файла
Можно сделать так, чтобы при изменения файла создавалась его резервная копия. Для этого используется ключ -B :
Если вы измените файл и сохраните изменения, то будет создана резервная копия файла, с содержимым файла, которое было до изменения. Имя резервной копии соответствует имени исходного файла со значком тильды
Источник