Linux nano нумерация строк

How to Show Line Numbers in Nano Editor?

Do you wish you had Nano line numbers? Well, now you can; read on to find out how to show line numbers in Nano editor.

How to Show Line Numbers in Nano Editor?

List of content you will read in this article:

The nano editor is a text editor included in many Unix-based systems. It is a small, lightweight editor that is easy to use and perfect for making simple changes to text files. If you’re new to the nano text editor, you may wonder how to show line numbers in Nano. This can be helpful when working with long files or finding a specific line of code.

How to Show Line Numbers in Nano? [Nano Line Numbers]

There are 4 methods to show line numbers in nano, and they are as follows:

Method 1:

You can directly use the following command to display line numbers in Nano:

nano —linenumbers [filename]

nano —linenumbers testfile.txt

Method 2:

You can press Alt +Shift + 3 key combinations to display line numbers quickly.

Method 3:

You can compile Nano from scratch:

git clone git://git.savannah.gnu.org/nano.git;cd nano;./autogen.sh;./configure;sudo make install

Then, in your /.nanorc file, add the following codes, do not worry if this file is empty. This file is not existed by default:

# include all the preexisting configs
include «/usr/share/nano/*.nanorc»
set linenumbers

Method 4:

You can use CTRL + C to display the current line number.

Also, to display the line & column number, you could just add the -c parameter when running nano editor:

Conclusion

You can easily set line numbers in your nano editor using 4 methods. Line numbers are important for users to get references on which line they are working on. Enabling them will help them understand and find an error in any lines. In this article, we have explained nano show line numbers commands. If you have any questions, you can ask them in the comment box.

People are also reading:

Источник

How to show line numbering in nano when opening a file

Starting from nano 2.7.1 you can open file with -l ( —linenumbers ) flag to display lilne numbers beside the text.

Best way is probably to edit the Nano config file: the example config file is located at /usr/share/doc/nano/examples/sample.nanorc . Copy this file to your ~/.nanorc and start editing from there.

Читайте также:  Сервер терминалов линукс 1с

7 Answers 7

The keyboard combination to display the current line number whilst you are using nano is CTRL + C .

Alternatively, to display the line & column number position you could just use the -c parameter when launching nano i.e:

To make this permanent, nano uses a configuration in your home folder ~/.nanorc

Thus to display line numbers always when using nano.

(don’t worry if its empty — this file doesn’t exist by default)

N.B. the deprecated syntax set const is shown in the animation

enter image description here

Since you are using line numbers remember you can use ALT + G to jump to a specific line number.

If you are in a tty, an alternative to CTRL+C is F11 and an alternative to ALT+G is F13 (which doesn’t exist on my keyboard) or Ctrl+_ (Ctrl+Shift+-).

Note that -c might not behave the way people are expecting. It won’t prefix each line with the number (like less -N ), it just makes the status box at the bottom of the screen permanent.

I agree with @IanDunn, this is the wrong answer. Add set linenumbers instead (only works in recent versions).

The permanent solution listed here no longer works in ubuntu 16.04+. Does anyone have an updated solution to permanently activating this setting in Ubuntu 16.04+ ?

@DanRan why it should not work? The post has high vote so it might work. the better the answer the higher the vote? Welcome to the SE Network.

Accidentally found nice shortcut: Alt + # , which in some keyboard layouts can be done with Alt + Shift + 3 .

click me gently

Add set linenumbers to .nanorc to make it permanent. If the shortcut doesn’t work try Modifier key + # .

According to the man page for GNU nano 2.9.3 (also verified on version 4.8) , you have two options for automatically opening with line-numbers shown and one for toggling them on/off once nano is open:

Command Line Flags

You can use the -l or —linenumbers flags.

-l, --linenumbers Display line numbers to the left of the text area.
nano -l foo.txt nano --linenumbers foo.txt 

Via the config file(s)

Alternatively, according to the man page for nanorc, you can add set linenumbers in ~/.nanorc , $XDG_CONFIG_HOME/nano/nanorc or ~/.config/nano/nanorc .

INITIALIZATION FILE nano will read two configuration files: first the system's nanorc (if it exists), and then the user's nanorc (if it exists), either ~/.nanorc or $XDG_CONFIG_HOME/nano/nanorc or ~/.config/nano/nanorc, whichever is encountered first. See nanorc(5) for more information on the possible contents of those files.
set linenumbers Display line numbers to the left of the text area.

So the contents of my ~/.nanorc file are simply:

1 set linenumbers 2

Via a key bindings

Not exactly what the OP was asking for, but for completeness you can also toggle line number on/off via the default keybinding (as of v4.8) of Alt+N .

Читайте также:  Утилита ip linux dhcp

Alternatively you can rebind this key via the man file mentioned method:

REBINDING KEYS Key bindings can be changed via the following three commands: bind key function menu Rebinds the given key to the given function in the given menu (or in all menus where the function exists when all is used).
The format of key should be one of: ^X where X is a Latin letter, or one of several ASCII characters (@, ], \, ^, _), or the word "Space". Example: ^C. M-X where X is any ASCII character except [, or the word "Space". Example: M-8. Sh-M-X where X is a Latin letter. Example: Sh-M-U. By default, each Meta+letter keystroke does the same as the corresponding Shift+Meta+letter. But when any Shift+Meta bind is made, that will no longer be the case, for all letters. FN where N is a numeric value from 1 to 24. Example: F10. (Often, F13 to F24 can be typed as F1 to F12 with Shift.) Ins or Del. Rebinding ^M (Enter) or ^I (Tab) is probably not a good idea. On some terminals it's not possible to rebind ^H (unless --raw is used) because its keycode is identical to that of the Backspace key. Valid function names to be bound are: . linenumbers Toggles the display of line numbers in front of the text.

Regarding alternate config files:

In response to comments about alternate config files, from the description of man nanorc :

During startup, nano will first read the system-wide settings, from /etc/nanorc (the exact path might be different on your system), and then the user-specific settings, either from ~/.nanorc or from $XDG_CON‐ FIG_HOME/nano/nanorc or from ~/.config/nano/nanorc, whichever is encountered first.

I would not typically advise others to change the system-wide config file, unless you have a good reason to do so, as it will likely be overwritten during any updates, and is not likely to be included in system backups, which typically only include the home directory.

Using with sudo

As noted by a commenter, this may not work as expected if you have to use sudo with nano, e.g. sudo nano myFile . This is because when you use sudo you are doing whatever comes after sudo as the «super user», thus the name (super user do ..). If you edited your non-super user config file (e.g. ~/.nanorc or /home/myUserName/.nanorc ) this will not be run when you use sudo as you are not running nano as myUserName any longer. Thus, you have a few options.

  1. The simplest is just to use the -l flag and it will work as is.
  2. Copy the contents of your ~/.nanorc to /root/.nanorc as this represents the home directory for the super user. Assuming you have your ./nanorc file setup as you like, and you don’t already have a /root/.nanorc file then you can just run sudo cp /home/myUserName/.nanorc /root/ . Note this will overwrite any existing nanorc file in /root and you must replace myUserName with your actual user name. I didn’t test, but I’d guess you can’t use the tilde operator, i.e «sudo cp ~/.nanorc /root/ as it would likely interpret this to be /root` rather than your username as again, you’re telling it «super user do cp from home directory».
Читайте также:  Hardware acceleration nvidia linux

Источник

Как показать нумерацию строк в нано при открытии файла

Есть ли способ заставить nano автоматически показывать нумерацию строк при каждом открытии файла?

7 ответов

Комбинация клавиш для отображения текущего номера строки при использовании nano — это CTRL + C.

В качестве альтернативы, чтобы отобразить позицию номера строки и столбца, вы можете просто использовать -c параметр при запуске нано т.е.

Чтобы сделать это постоянным, nano использует конфигурацию в вашей домашней папке ~/.nanorc

Таким образом, чтобы отображать номера строк всегда при использовании нано.

(не волнуйтесь, если он пуст — этот файл не существует по умолчанию)

NB устаревший синтаксис set const показано в анимации

введите описание здесь

Поскольку вы используете номера строк, помните, что вы можете использовать ALT + G для перехода к определенному номеру строки.

Случайно нашёл приятный ярлык: Alt + Shift + 3.

щёлкни меня нежно

Начиная с GNU nano 2.9.3, вы можете использовать -l или —linenumbers флаги.

Я также проверяю это set linenumbers в /home//.nanorc работает.

Компиляция Nano из источника:

git clone git://git.savannah.gnu.org/nano.git;cd nano;./autogen.sh;./configure;sudo make install 

Затем добавьте следующее к вашему .nanorc файл:

Вы можете использовать Meta + #, чтобы включать и выключать номера строк в Nano.

Если nano -c filename не работает, используй nano filename затем Ctrl + _ . Он попросит вас ввести номер строки.

Это 2021 год. Вопрос ОП все еще актуален, но многие ответы здесь относятся к более старой версии . Я не представляю этот ответ как «последнее слово» — только как обновление.

Экран nano по умолчанию состоит из пяти областей. Сверху вниз это: строка заголовка, пустая строка, окно редактирования, строка состояния и две строки справки.

Где отображать номера строк?

Номера строк могут отображаться в одном из двух мест:

Отображение строки состояния просто обновляет номер строки (и столбца) курсора/точки вставки по мере его перемещения в окне редактирования. Номера строк в окне редактирования располагаются на левом поле. Номер строки можно отобразить либо в окне редактирования, либо в строке состояния.

Отображение номеров строк в окне редактирования:

Существует несколько методов (это не обязательно полный список):

    Перед открытием файла: Отредактируйте/создайте файл со следующей строкой:

Отображать номера строк в строке состояния

Резюме

Все они работают на сегодняшний день: Ubuntu 20.04, nano —version = GNU nano, версия 4.8, хотя в документации есть небольшие расхождения .

Источник

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