Regex-based matching and sustitution with nano?

26.2k Views Asked by At

I am aware of nano's search and replace functionality, but is it capable of using regular expressions for matching and substitution (particularly substitutions that use a part of the match)? If so, can you provide some examples of the syntax used (both for matching and replacing)?

I cut my teeth on Perl-style regular expressions, but I've found that text editors will sometimes come up with their own syntax.

5

There are 5 best solutions below

6
On BEST ANSWER

You need to add, or un-comment, the following entry in your global nanorc file (on my machine, it was /etc/nanorc):

set regexp

Then fire up a new terminal and press CTRL + / and do your replacements which should now be regex-aware.

EDIT


Search for conf->(\S+):

enter image description here


Replace with \1_conf

enter image description here


Press a to replace all occurrences:

enter image description here


End result:

enter image description here

6
On

My version of nano has an option to swtich to regex search with the meta character + R. In cygwin on Windows, the meta-key is alt, so I hit ctrl+\ to get into search-and-replace mode, and then alt+r to swtich to regex search.

0
On

This is a bit old, just updating the search index.

Nano 5.5 uses the ASCII column from this same table.

Thanks to @S P Arif Sahari Wibowo ,

I found the answer here anyway (same wiki link): https://en.wikipedia.org/wiki/Regular_expression#POSIX_basic_and_extended

3
On

The regular expression format / notation for nano use "Extended Regular Expression", i.e. POSIX Extended Regular Expression, which is used by egrep and sed -r, this include metacharacters ., [ and ], ^, $, (, ), \1 to \9, *, { and }, ?, +, |, and character classes like [:alnum:], [:alpha:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:].

For more complete documentation you can see manual page, man 7 regex in Linux or man 7 re_format in OS X. This page may give you same information as well: https://en.wikipedia.org/wiki/Regular_expression#POSIX_basic_and_extended

Unfortunately in nano there seems to be no way to match anything that span across multiple lines.

0
On

I was recently faced with the problem of inserting text at the beginning of everyline that started with a numerical digit. For that the only way to distinguish this from text i didn't want to change was the previous new line.

Playing around with the information provided in this answer I was able to do it and decided to add it to the answer in case somebody else faces the same situation.

To search for the beginning of the line followed by a number and then insert "Text String" at the beginning of each line that starts with a number:

\ then "(^[0-9])" press carry return, then: "Text String 1" press carry return and the select yes, if it does what you want next press a for all. Omit the " quotation marks.