3

I want to find specific characters/strings with nano and delete all occurrences. How can this be done with nano and can this even be done?

1 Answers1

5

Find and Replace

This use of "Find and Replace" works in Nano 5.8: (I have tested)

  • Press Alt-R (default keybinding)
  • Search (to replace): Enter the string you want to search for, and press Enter
  • Replace with: Just press Enter (leaving the replace string blank)
  • Replace this instance? Press A to repace all instances of string with no characters (thus removing it)

Upgrade Nano to a newer version (for 20.04 LTS)

There are 2 options: (I have tested both)

  1. Uninstall the deb version of Nano, and install the snap version (currently 5.7): sudo snap install nano --classic

  2. Download a newer and compatible Debian package (currently 5.4 available) and install: sudo apt install ./nano_5.4-2_amd64.deb

Artur Meinild
  • 26,018
  • I already tried this. Unfortunately, it didn't work. All occurrences were replaced with a space instead of being removed. – Alpha-Craft Apr 20 '22 at 17:53
  • Which version of Nano are you using? I've tested on 5.8 and it works. – Artur Meinild Apr 20 '22 at 17:55
  • 2
    Then you most likely did type a space char at the "Replace with:" prompt. Nano is well behaved IMO. – Hannu Apr 20 '22 at 19:04
  • I think I know the problem. I think it did remove the characters. I had multiple lines and each of them contained one character. I wanted to remove the line but it did just remove the characters and not the line break. – Alpha-Craft Apr 22 '22 at 13:00
  • Yeah OK, I don't think you can search and replace line breaks with Nano. – Artur Meinild Apr 22 '22 at 13:05
  • @ArturMeinild Yes you can (but not by default without external commands)! :) See https://stackoverflow.com/questions/25959610/nano-insert-newline-in-search-and-replace/73945051#73945051 (This describes how to make a keyboard shortcut that lets you do Python-style regular expression substitutions, which allow searching/replacing new lines). – Brōtsyorfuzthrāx Oct 05 '22 at 07:22
  • Interesting ... – Artur Meinild Oct 05 '22 at 07:24
  • If you don't need full regular expressions, in the Python file mentioned in my answer I linked to above, you could replace re.sub(regex, replacement, myString) with myString.replace(searchCriteria, replacement), and it'll still do new lines (without having to use regular expressions). – Brōtsyorfuzthrāx Oct 05 '22 at 07:29