Using nano in linux

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).
Читайте также:  Product key windows sku

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.

Источник

Как использовать Nano, текстовый редактор командной строки Linux

При работе в командной строке довольно часто возникает необходимость создавать или редактировать текстовые файлы. Два самых мощных и популярных редактора командной строки — это Vim и Emacs. У обоих из них крутая кривая обучения, которая может напугать новых пользователей. Для тех, кому нужен простой редактор, есть nano.

GNU nano — это простой в использовании текстовый редактор командной строки для операционных систем Unix и Linux. Он включает в себя все базовые функции, которые вы ожидаете от обычного текстового редактора, такие как выделение синтаксиса, несколько буферов, поиск и замена с поддержкой регулярных выражений, проверка орфографии, кодировка UTF-8 и многое другое.

В этом руководстве объясняется базовое использование редактора nano, в том числе как создать и открыть файл, отредактировать файл, сохранить файл, найти и заменить текст, вырезать и вставить текст и многое другое.

Установка Nano

Текстовый редактор Nano предварительно установлен в macOS и большинстве дистрибутивов Linux. Чтобы проверить, установлен ли он в вашей системе, введите:

Результат будет выглядеть примерно так:

Если в вашей системе не установлен nano, вы можете установить его с помощью диспетчера пакетов вашего дистрибутива.

Установите Nano в Ubuntu и Debian

Установите Nano на CentOS и Fedora

Открытие и создание файлов

Чтобы открыть существующий файл или создать новый файл, введите nano и имя файла:

Это открывает новое окно редактора, и вы можете начать редактирование файла.

Внизу окна находится список основных сочетаний клавиш для использования с редактором nano.

Все команды начинаются с символа ^ или M Символ каретки ( ^ ) представляет собой Ctrl . Например, команды ^J означают одновременное нажатие Ctrl и J Буква M представляет собой Alt .

Вы можете получить список всех команд, набрав Ctrl+g .

Чтобы открыть файл, у вас должны быть права на чтение файла.

Если вы хотите открыть файл с курсором на определенной строке и символе, используйте следующий синтаксис:

Если вы опустите character_number курсор будет помещен на первый символ.

Редактирование файлов

В отличие от vi, nano — это немодальный редактор, что означает, что вы можете начать вводить и редактировать текст сразу после открытия файла.

Чтобы переместить курсор на определенную строку и номер символа, используйте команду Ctrl+_ . Меню в нижней части экрана изменится. Введите число (а) в поле «Введите номер строки, номер столбца:» и нажмите Enter .

Поиск и замена

Чтобы найти текст, нажмите Ctrl+w , введите поисковый запрос и нажмите Enter . Курсор переместится к первому совпадению. Чтобы перейти к следующему совпадению, нажмите Alt+w .

Если вы хотите найти и заменить, нажмите Ctrl+ . Введите поисковый запрос и текст, который нужно заменить. Редактор перейдет к первому совпадению и спросит, заменить ли его. После нажатия Y или N он перейдет к следующему матчу. Нажатие A заменит все совпадения.

Читайте также:  Windows 10 профессиональная мультиязычная лицензия цифровая версия

Копирование, резка и склеивание

Чтобы выделить текст, переместите курсор в начало текста и нажмите Alt+a . Это установит отметку выбора. Переместите курсор в конец текста, который хотите выделить, с помощью клавиш со стрелками. Выбранный текст будет выделен. Если вы хотите отменить выделение, нажмите Ctrl+6

Скопируйте выделенный текст в буфер обмена с помощью команды Alt+6 . Ctrl+k обрежет выделенный текст.

Если вы хотите вырезать целые строки, просто переместите курсор на строку и нажмите Ctrl+k . Вы можете вырезать несколько строк, несколько раз нажав Ctrl+k .

Чтобы вставить текст, переместите курсор туда, где вы хотите поместить текст, и нажмите Ctrl+u .

Сохранение и выход

Чтобы сохранить изменения, внесенные в файл, нажмите Ctrl+o . Если файл еще не существует, он будет создан после его сохранения.

Чтобы выйти из nano, нажмите Ctrl+x . Если есть несохраненные изменения, вас спросят, хотите ли вы сохранить изменения.

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

Настройка Nano (nanorc)

Когда nano запущен, он считывает свои параметры конфигурации из общесистемного файла конфигурации /etc/nanorc и из пользовательских файлов

/.nanorc если файлы присутствуют.

Параметры, указанные в пользовательских файлах, имеют приоритет над глобальными параметрами.

Посетите страницу nanorc для получения полного списка всех доступных опций.

Подсветка синтаксиса

Nano поставляется с правилами подсветки синтаксиса для большинства популярных типов файлов. В большинстве систем Linux файлы синтаксиса хранятся в каталоге /usr/share/nano и по умолчанию включены в файл конфигурации /etc/nanorc .

Самый простой способ включить выделение для нового типа файла — скопировать файл, содержащий правила выделения синтаксиса, в каталог /usr/share/nano .

Установите Nano в качестве текстового редактора по умолчанию

По умолчанию в большинстве систем Linux текстовый редактор по умолчанию для таких команд, как visudo и crontab , установлен на vi. Чтобы использовать nano в качестве текстового редактора по умолчанию, вам необходимо изменить EDITOR среды VISUAL и EDITOR .

Пользователи Bash могут экспортировать переменные в файл

Базовое использование нано

Ниже приведены основные шаги для начала работы с nano:

  1. В командной строке введите nano а затем имя файла.
  2. При необходимости отредактируйте файл.
  3. Используйте команду Ctrl-x для сохранения и выхода из текстового редактора.

Выводы

В этом уроке мы показали вам, как использовать текстовый редактор Gnu nano. Это популярный текстовый редактор среди пользователей Linux, требующий небольшого обучения.

Для получения дополнительной информации о Gnu Nano посетите официальную страницу документации nano .

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

Источник

How to Install and Use Nano Text Editor: A Beginner’s Tutorial

In this tutorial, you will learn how to use and install Nano, a popular text editor of Unix and Linux operating systems. Nano comes with many powerful features and allows you to edit and create various files on your computer or server. So let’s get right to it.

How to Install Nano Text Editor

This process depends on the operating system you are using. Some, like macOS or Linux distros, may already come with the Nano text editor pre-installed.

To check, simply use the following command:

If you see an output that tells you a version number, you can skip this section.

Installing Nano on Debian/Ubuntu

To install Nano text editor on Debian or Ubuntu machines, execute the following command:

Then, wait for the installation process to finish.

The sudo part is meant for running this command as a root user. This means you may be prompted to enter a password in case you are currently not logged in as a root user.

Installing Nano on CentOS/RHEL

We can run this command to install Nano text editor on CentOS or RHEL based platforms:

That is it to install Nano. As soon as the setup ends, you can use it immediately.

How to Use Nano Text Editor

In this part, you are going to learn how to open and close files. Also, how to search and replace text. Then, we’ll show you some editing tips and other basic commands that you can use in Nano text editor.

How to Open and Close the Nano Editor

The main syntax to open Nano and to edit a certain file is:

Let’s say we want to open a file named demo.txt. The command would look like:

You can open various file types, like .txt, .php, .html, and so on. Just keep in mind that if you want to open a specific file, you will need to be in the directory where the file is located.

However, if you are in another folder, and you want to open a file (demo.txt) in /path/to/directory, you can enter this line instead:

If you enter a file name and that file is not present in the directory, Nano will create a new file. Meanwhile, if you only execute the nano command without specifying the file name, Nano text editor will create an empty untitled file and ask for a name when you exit the editor.

After running the nano command, a new window will pop up where you can freely edit the file. Below is what the interface of the Nano text editor looks like. Just use the arrow keys on your keyboard to move the cursor around the text.

Читайте также:  Windows device installer download

At the bottom of the window, you can find some shortcuts to use with the Nano editor. The “^” (caret) means that you must press CTRL (Windows) or control (macOS) to use the chosen command. Here are a few examples.

  • Press CTRL + O to save the changes made in the file and continue editing.
  • To exit from the editor, press CTRL + X. If there are changes, it will ask you whether to save them or not. Input Y for Yes, or N for No, then press Enter. But if there are no changes, you will exit the editor right away.

Take note that whenever you are opening an important configuration file, it is recommended to use the -w option. It will open the file in a standard format. If you don’t use this option, nano will wrap the text to fit the display by default. The command will be like this:

How to Search and Replace Text

To search in the text, press CTRL + W. Insert your value and press Enter. To continue searching for the same text string, use ALT + W.

If your goal is to find and replace a text, press CTRL+W and then CTRL+R to enter the text that you want to search and the text that will replace it. The editor will then take you to the first instance of the text. You can press Y to replace one text or A to replace all instances.

Should you want to go back after typing a shortcut, just use CTRL + C to cancel the current process.

How to Edit Text

These are the commonly used shortcuts when editing a text in Nano.

  • To select text, go to the beginning of the desired text and press ALT + A. This will set a mark for selecting. Then, you can move over the text with arrow keys.
  • Press ALT + 6 to copy the selected text to the clipboard.
  • To cut the highlighted text, press CTRL + K.
  • If you want to paste the text, navigate to the intended place and press CTRL + U.

Basic Nano Text Editor Commands

We have compiled the most useful commands to help you utilize the Nano text editor more effectively.

Command Explanation
CTRL + A Lets you jump to the beginning of the line.
CTRL + E Lets you to jump to the end of the line.
CTRL + Y Scrolls page down.
CTRL + V Scrolls page up.
CTRL + G A Help window will pop out and show you all the available commands.
CTRL + O To save the file. Nano will ask you to edit or verify the desired file name.
CTRL + W Search for a specified phrase in your text. Press ALT + W to search for the same phrase again.
CTRL + K It cuts the entire selected line to the cut buffer (similar to clipboard).
CTRL + U To paste the text from the cut buffer into the selected line.
CTRL + J Justifies the current paragraph.
CTRL + C Shows the current cursor position in the text (line/column/character).
CTRL + R Opens a file and inserts it at the current cursor position.
CTRL + X To exit Nano text editor. It prompts a save request if you made any changes to the file.
CTRL + \ Replaces string or a regular expression.
CTRL + T Invokes the spell checker, if available.
CTRL + _ Lets you go to the specified line and column number.
ALT + A To select text. You can combine this command with CTRL + K to cut a specific part of the text to the cut buffer.

Why You Should Use Nano Text Editor

When it comes to editing text via command line, Nano is considered one of the easiest tools to use. It beats Vim and Emacs editor, which are known to be overwhelming, especially for novice Linux users.

Though it’s simple, Nano editor packs a complete feature set. To name a few, it allows you to copy, paste, select, and search text. Furthermore, there is a bottom bar inside the editor that shows you useful shortcuts. All in all, the Nano editor is suitable for both advanced users and beginners.

You can often find it prepackaged on Linux PC or server. For example, Hostinger includes Nano text editor on its shared hosting and VPS plans.

Conclusion

Nano is a popular and versatile terminal-based text editor in Linux. It is a perfect fit for beginners and professionals who are looking for a complete tool to modify their text.

In this tutorial, you have learned how to use the Nano text editor. We have shown you a lot of useful commands and editing tips to improve your workflow. Now, we hope that you can easily edit text without having to download and re-upload the file.

Good luck, and be sure to check our other SSH and VPS tutorials.

Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.

Источник

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