2

I have a file that contains records with tab separated format but in two lines, I want to arrange records in one line with tab separated values using vim editor pattern match.

Ex.

Abc     PQR     XYZ     NMW
    XYX     PQR     LMW
PLX     PXQ     LPN     PWF
    XYQ     PLP     PMQ    LWP

I want to add each second line of the record to the first line of records. The output format that I want is like this.

Abc     PQR     XYZ     NMW    XYX     PQR     LMW
PLX     PXQ     LPN     PWF    XYQ     PLP     PMQ     LWP

I tried the following command to solve my problem.

:%s/\n(\w\+.*)/\t\1/cgi

This is replacing each line data with tab at front except first line.

How can we solve this using vim pattern match and replace?

3 Answers 3

8

How about

:%s/\n\s\+/\t/gc

That will find any newline character that is followed by white space and replace all of it with a tab thereby combining your lines.

1
  • If it worked don't forget to mark this as the correct answer. Thanks
    – David King
    Dec 22, 2015 at 16:37
2

If you know the first line will always start with a letter and the second line will always start with a tab, the most vimmy way to do this would probably be to use :g (run an ex command on all lines matching a regex) and j! (join without removing whitespace). Check out help :g and help :j. Combining these, you'd get

:%g/^\w/j!
1

You can do it easily with paste:

paste -sd'\0\n' file

In vim:

:%!paste -sd'\0\n' -
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .