skip to Main Content

I have a file with following pattern

property1:  value1
property2:  value2
property3:  value3
property4:  value4
property5:  value5

Value could be ipv4/ipv6 ip address, number, string etc.

How can this be modified to something like using available text editor tools:

property1  "value1";
property2  "value2";
property3  "value3";
property4  "value4";
property5  "value5";

2

Answers


  1. One simple way is to record a macro.

    1. Place a cursor on first line, first column
    2. Make sure you are in "normal" mode.
    3. Start recording a macro into "q" register by typing "qq"
    4. f:xwi"<Esc>$a";<Esc>0j
    5. Stop recording by typing q
    6. Transform next line by typing @q
    7. Repeat macro by typing @@

    You will see your file transforming.

    Detailed explanation of step 4:

    • f<char> moves the cursor to next occurence of . That’s how we get from the first column of the line to the index of :.
    • x delete char under cursor.
    • w moves us to next word, essentialy we are jumping over the whitespace
    • i enters insert mode, so we can type new characters. We are inserting " and exiting insert mode by pressing Esc.
    • $ gets us to the end of the line.
    • a again enters insert mode, but cursor is placed after current position (essentialy $a means append to end of the line)
    • We insert last chars "; and we again exit insert mode with Esc.
    • 0 moves to the beginning of the line, and j moves one line down. This last step is so the macro can be repeated without much thinking.
    Login or Signup to reply.
  2. That’s a job for sed, not vim. Using any POSIX sed:

    $ sed 's/:([[:space:]]*)(.*)/1"2";/' file
    property1  "value1";
    property2  "value2";
    property3  "value3";
    property4  "value4";
    property5  "value5";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search