odessos
odessos

Reputation: 243

How to select all lines maching a pattern?

Is it possible to select all lines matching a pattern?

To illustrate, using column :

      1     2  3                                   1 2 3
   2     1  4      select all lines matching 1     2 1 4
1 2      2            :'<,'>!column -t             1 2 2
  3   2    3            ->                           3   2    3
 1 1   3                                           1 1 3
    4 4     4                                        4 4     4

Upvotes: 3

Views: 11327

Answers (3)

aglien
aglien

Reputation: 121

If I well understood your question, the answer is quite simple:

qregisterq
:g/pattern/y REGISTER

The first line is necessary to clean up the register's content, if you used it before. In the second line it's important to capitalize the register's name because that means that you intend to append the content of each matching line, instead to substitute it.

To paste the matching lines simply do:

"registerp

or even more simple:

p

because p copy the content of the last register used.

For example, to select all lines matching 1 (using register a):

qaq
:g/1/y A

and then:

"ap

Upvotes: 12

Jason Hu
Jason Hu

Reputation: 6333

according to you example, i guess you want to delete all blank prefix where the lines having 1 in it. so in vi, we could do it without selecting:

:%s/\s*\(.*1.*\)$/\1

UPDATE:

always a way to solve your problem in a traditional vi way.

according to your new example, i think you want to delete all blanks in the lines with 1 in it. so we can:

:g/1/s/\s\+//g

or maybe you want to have one space left for alignment:

:g/1/s/\s\+/ /g

g/1/ matches all lines in the file with 1 in it, s/\s\+//g substitutes all blanks to nothing globally in the scope of one line.

Upvotes: 2

Zach
Zach

Reputation: 4792

Vim doesn't have the ability to match multiple separated lines by default.

You could look at this script, or this one (more up to date) and see if it works for you.

However, if you are just selecting the lines to perform a command on them, you can use the :g command to perform the command directly on those lines.

:g/regex/ex command

So for example:

:g/hello/d

Will delete all lines that match the regex hello

With the multiple cursors plugin (also linked above) you can select multiple separated lines that match a regex:

:% MultipleCursorsFind Regex

This will select the lines for you and then you can execute any commands you like on them.

Upvotes: 3

Related Questions