Linux nano copy and paste

Использование редактора 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

Читайте также:  Linux version used in android

Чтобы прекратить поиск, нажмите:
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 :

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

Источник

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 Paste in Nano Editor

Today’s article will show you which keyboard shortcuts you will need to use to copy and paste in Nano.

List of content you will read in this article:

Nano is the most simple text editor for Linux that is command-line based. It includes all of the usual text editor functionality, such as syntax highlighting, multiple buffers, search and replacements with regular expression support, typo correction, and UTF-8 encoding. When you have copied any text, you need to know how to paste it. In this guide, we have guided tutorials on how to copy and paste using the shortcut keys available in the nano text editor.

How to Copy and Paste in Nano Editor?

In a nano text editor, we can copy using the following steps:

  • Set the target by moving the cursor to the beginning of the text and pressing CTRL + 6.
  • Using the arrow keys, highlight the text you want to copy.
  • To copy, hold ALT + 6.
  • To paste, move the cursor to the target position and click CTRL + U.

Conclusion

Using the following commands and shortcut keys, we can paste the text into the nano editor. By using CTRL + 6, you can easily copy the text in the nano editor. You can paste it wherever you want in the editor by using ALT+6. We hope the article has helped you to copy in Nano Editor without having trouble.

Источник

Читайте также:  Драйвера hp1020 для windows 10
Оцените статью