6

How can I selected, for instance, 5 lines of code, and replace all instance of myObject1 with myObject2?

If subsequent lines of code contain myObject1 reference that I wish not to change. This way I can quickly apply of find & replaces in this scope of code very conveniently without worrying about side effects.

Is this possible?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Alex Bollbach
  • 4,370
  • 9
  • 32
  • 80

2 Answers2

6

Yes, it is possible.


Classic UI

  1. Open the "Find and Replace" dialog box either by choosing in the top menu Edit > Find > Replace or using the dedicated shortcut Ctrl+R ( R on Mac).
  2. Enter your search and replace terms.
  3. Select some area in your code.
  4. Press the dedicated button to only search within a selection: enter image description here

Now if you press "Replace All", only the items found inside your selection will be replaced.


New UI

In the new UI of IntelliJ IDEA the "Search In Selection" option is in another place (kudos to @Chris for pointing this out):

  1. Open the "Find and Replace" dialog box either by choosing in the top menu Edit > Find > Replace or using the dedicated shortcut Ctrl+R ( R on Mac).
  2. Enter your search and replace terms.
  3. Select some area in your code.
  4. Open "Filter Search Results" dialog by pressing the dedicated button and click on the first option "Search In Selection". enter image description here

Now if you press "Replace All", only the items found inside your selection will be replaced.

NOTE

You can also open the "Filter Search Results" dialog using the shortcut (Ctrl+Alt+F on Windows/Linux, F on macOS), but in this case it is important that the cursor is inside the "Search" field.


In similar way you can perform just a search (i.e. without replace) inside a selected area in your files. Look inside the Edit > Find menu for more interesting options.

Here is the official IntelliJ IDEA documentation that covers this topic: Find in selection.

informatik01
  • 16,038
  • 10
  • 74
  • 104
  • For everyone whos missing the icon shown here: In the new IntelliJ UI the icon is gone, and the action was moved under the filter icon instead. However the double CTRL + R (Command + R) still works. – Chris Jun 13 '23 at 08:38
  • @Chris Thank you for pointing this out. I have updated my answer for the New UI. – informatik01 Jun 18 '23 at 00:15
-1

for me it is CTRL + H or CTRL + SHIFT + H

Eduard Braun
  • 370
  • 3
  • 5
  • This answer is not correct. `Ctrl + H` _by default_ opens **Type Hierarchy** (top menu `Navigate > Type Hierarchy`). – informatik01 Mar 15 '23 at 00:38