tags:

views:

99

answers:

1

I've a big file with lines that look like

2 No route to specified transit network

3 No route to destination

i.e. a number at the start of a line followed by a description.

And I'd like to transform that for use as a struct initializer

{2,"No route to specified transit network"},

{3,"No route to destination"},

How would I do this ?

+8  A: 

Try

:%s/^\(\d\+\)\s\(.*\)$/{\1, "\2"},/

This uses search-and-replace and searches for a line starting with a digit, followed by whitespace, followed by arbitrary text until the end of the line. This is replaced by the pattern you specified.

Or, using “more magic” (thanks to Al in the comments):

:%s/\v^(\d+)\s(.*)$/{\1, "\2"},/
Konrad Rudolph
+1. And use `\d*` instead of `\d` if some of the numbers have multiple digits.
Stephan202
Adjusted for my purpose to %s/^\(\d*\)[ ]*\s\(.*\)$/{\1, "\2"},/ . Thanks.
@Stephan202: \d\+ might be better than \d* if you want to ensure that there's at least one digit. Also, you could save a bit of backslashing with `:%s/\v^(\d+)\s(.*)$/{\1, "\2"},/` (`:help \v`). If you're sure they'll always be spaces, you could just do `:%s/\v^(\d+) +(.*)$/{\1, "\2"},/`
Al
AI: Thanks, I didn’t know about `\v` until now, very helpful.
Konrad Rudolph
Drive-by +1: \v is awesome. Who doesn't love something called "more magic?"
ojrac