3

I have a program that lists hostnames and IPs. Some hostnames have multiple IPs assigned to them. When I download the IP column .csv, it lists as such:

192.168.xx.xx
"192.168.xx.xx, 192.168.xx.xx"
192.168.xx.xx

I am putting the contents of this .csv file into a VI file. What I would like to do is figure out how to script it so that the lines with 2 IPs (with the " " and ,) move one of the IPs to a new line and remove all of the " " and , so that I can easily run this through a Powershell script to ping each and get their up/down status.

Goal would be to get this file:

192.xx.xx
192.xx.xx
192.xx.xx
192.xx.xx

Any suggestions? Thanks so much!

  • 5
    Are those meant to be on separate lines? – Antony Jun 23 '16 at 20:07
  • What did you try? – romainl Jun 24 '16 at 5:16
4

You can use the :substitute command for this:

:%s/"//g | %s/, /\r/g

First replace all quotation marks with nothing (I assume there will be no escaped "s since these are just IP addresses). Then (| is the command separator) replace all ', ' with linebreaks (\r).

References:

  • 1
    After @TommyA's edit I would recommend changing substitution to :%s/"\(.*\),\(.*\)"/\1\r\2/g – Tumbler41 Jun 23 '16 at 20:31
  • 1
    @Tumbler41 That's assuming that there's only two IPs in each field. If this was a common thing that needs to be done I would make a command with: %s/^"\(.*\)"/\=substitute(submatch(1), ',\s*', "\r", 'g')/g to be on the safe side. – Tommy A Jun 23 '16 at 20:41
  • 1
    Those are both more complicated ways of achieving the same result. – Antony Jun 23 '16 at 21:29
  • Ok, sorry. I read your expression wrong. Yeah, yours is fine. – Tumbler41 Jun 23 '16 at 21:38
  • Well, if you need performance, one command is probably faster. I guess I just prefer to keep things simple if possible. – Antony Jun 23 '16 at 21:45
2

You can use macros to do the same thing.

For removing ", do this.

qaqqa/"<CR>xn@aq

For removing , and replacing it with a new line,

qsqqs/,<CR>i<CR>xx@sq

Now, explanation:

qa - start recording a  macro and stores in register `a`
q - stops the macro (empties register content.
/" - find double quotes
<CR> - enter. Don't type <CR> but press enter instead of this.
x - delete the current character
n - find next occurrence
@a - replay the macro recursively
q stop the macro.

You can execute the macros by pressing @a and @s in normal mode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.