Rohan Büchner
Rohan Büchner

Reputation: 5403

GVim/Vim. How to delete all white space up to a certain word

I'm a .Net dev but recently started dabbling with Vim (or in my instance GVim) for when I need to do repetitive text editor type tasks.

My experience is basically non-existent. So please bear with me. Also I realize there are GUI tools or things I can make use of inside Visual Studio, but I'm trying out the Vim route as I'd like to master a new util/app every now and then.

Say I've got a text file which contains a lot of properties (could be any text though) like so:

    public string AccountNumber { get; set; }

    public string CustomerName { get; set; }

    public string ExpiryDate { get; set; }

    public string IdentityNumber { get; set; }

    public string OfferDate { get; set; }

I'd like to make use of the string replace method to delete everything up to, and after the property name.

e.g. end with:

 AccountNumber, 
 CustomerName, ... etc.

So far I've had success with

  • 1) Alt + left click + drag select all the preceding white space & delete
  • 2) :% s/public\ string\ //
  • 3) :% s/\ {\ get;\ set;\ }/,/

It's purely out of curiosity I'd like to find out if its possible to update my 2nd step to include the removal of the white space.

I realize the ^ character means beginning of the line and that (I think) \s means white space, but that's about where my knowledge ends.

I'm thinking something like?

:% s/^\s+string//

Upvotes: 0

Views: 1343

Answers (3)

Peter Rincker
Peter Rincker

Reputation: 45177

Using :normal would be an alternative to :s or a macro in this case:

:%norm 03dwelD

You may want to use a different range other than the whole file, %. I would suggest visually selecting the lines with V then execute :norm 03dwelD. After you type : your prompt will look like :'<,'>. This is correct.

For more help see:

:h :norm

Upvotes: 1

Fredrik Pihl
Fredrik Pihl

Reputation: 45670

one way to solve this is to record a macro

qq          # start recording macro into register q
0w          # move to first non-whitespace caracter. Omit this if no WS at start of line
d2w         # delete 2 words
w           # move a word forward
D           # delete to en of line 
q           # quit macro recording

standing at the beginning of a line, do @q For subsequent lines, repeat the macro using .

or, try the following substitution

:%s/^\s*public string\s*\([a-zA-Z]*\).*$/\1/ 

Upvotes: 3

Kent
Kent

Reputation: 195239

I came up with this,

%s/^\v\s*(\s*\w+){2}\s?(\w+).*/\2/g

precisely speaking, this line doesn't know which word is your "property". it just leave the 3rd word in the line there, remove anything else.

Upvotes: 2

Related Questions