3

I've a big file with lines that look like

2 No route to specified transit network

3 No route to destination

And I'd like to transform that for use in a programming language to

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

{3,"No route to destination"},

How would I do this ?

3
  • Do all of the lines begin with a number, followed by a space?
    – waiwai933
    Sep 2, 2009 at 9:30
  • You ask this question on StackOverflow too. That's not very cool for the Google ranking (duplicate contents) of the answer if someone has the same question later... ;-)
    – p4bl0
    Sep 2, 2009 at 9:43
  • Link to the question on Stack Overflow: stackoverflow.com/questions/1366682/…
    – las3rjock
    Sep 2, 2009 at 10:42

4 Answers 4

8

The basic conversion is,

sed 's|^\([0-9]\)\(.*\)|{\1,"\2"}|g' file.txt > file2.txt

in vim,

:%s/\([0-9] \(.*\)/{\1,"\2"}/g

This will cover lines starting with the format,

N text on the line...

Where N is a single digit number.
Can be extended further for other forms.

4

In your case, a simple regular expression is enough (and the best solution). However, in some other cases, recording a macro might be better.

There is a simple macro example at vim documentation, section 12.1, and further description at :help q

In a nutshell:

  1. Type q followed by a letter (the letter is the register where the macro will be recorded).
  2. Do some commands, modify your text as needed, use all power of Vim.
  3. Move the cursor to the next line.
  4. Press q to stop recording.

To play a macro, press @ followed by the letter where the macro was recorded. To re-play the last macro, press @@. Type a number before playing a macro to repeat it as many times as needed.

So, in your case, to transform the lines like this:

2 No route to specified transit network
{2, "No route to specified transit network"},
  1. Position your cursor at one of the lines.
  2. Press qa (the choice of register a was arbitrary).
  3. Press exactly this (including quotes and spaces) I{<esc>f cl, "<esc>A"},<esc>j
  4. Press q to stop recording.
  5. Press 100@a and be happy watching the macro being played. :-)

I'll leave to the reader the explanation of each command from step 3. ;-)

Of course, this is not the only solution. You could have done the step 3 in many different ways.

1

Does this vim command do what you want ?

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

You must log in to answer this question.

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