4

I have a file which has contents like so:

size is X1 Identifier is Y1
size is X1 Identifier is Y1
size is X1 Identifier is Y1

I want to re-arrage the file so that I get

Identifier is Y1 size is X1 
Identifier is Y1 size is X1 
Identifier is Y1 size is X1 

How do I do this using vim find & replace? Or any other function in vim?

sshirgao
  • 291
  • 3
  • 9
  • what is the rule.. first three columns are shifted to end of line or everything until but not including Identifier is shifted and so on... you can use substitute command or normal mode commands(prefix a number to delete command with word as movement, move to end, use paste and so on) – Sundeep Aug 03 '17 at 06:30

4 Answers4

6

Use capturing groups and switch both groups

%s/\v(.*) (I.*)/\2 \1
Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
4

As you say "Or any other function in vim", I'll offer an alternative by recording a macro. Personally I like using macros for things like this because you perform the action you want to do once, which helps you to think through exactly what you want, then just repeat the same thing as many times as you need to.

There's almost certainly a more efficient way than the below, but hopefully this is a fairly straightforward way.

Start with your cursor anywhere in the first line.

qa (start recording a macro in register a - you can substitute the a for any other letter)

0 (move to the start of the line)

Next, perform whatever command you want to use to remove the first part of the line, for example: 3dw - if you need more complex rules to identify the part of the line to move, this is where you would do it.

$ (move to the end of the line)

aSPACEESCp (append a space at the end of the line, then paste the text we deleted previously)

j (move down a line, so we're in the next line when we finish this run of the macro)

q (stop recording)

Once you've completed this, the first line should be in the state that you want it, and your cursor will be in the second line. To repeat the above starting from your current position, just do:

@a (or whatever letter you chose in the first step in place of the a).

DaveyDaveDave
  • 9,821
  • 11
  • 64
  • 77
  • Worth adding that, if you change your mind part-way through recording the macro, you can stop recording it simply by pressing `q`, and start again. – DaveyDaveDave Aug 03 '17 at 08:00
2

I don't use vim that much, but the term you are searching for is "regex capture groups" which exist in nearly every regex implementation. Capture groups give you the parts of a matched pattern and let you reorganize them to your needs.

Here is a question which might contain your answer:

Similar question

2

:%s/\(size is \w*\) \(Identifier is \w*\)/\2 \1/g This works. I assumed that what you marked as X1, Y1 can be any word, hence \w*.