Link to home
Start Free TrialLog in
Avatar of oliversk
oliversk

asked on

Word replacement using regexp in vi or vim

Hi.

Suppose I have a file containing the lines:

   ID_SalesID mSalesId;
   ID_RefID mRefId;
   ID_CouponId mCouponId;

What pattern/regexp substitute command (in vi/vim) can I use such that I'm left with

mSalesId(NULL),
mRefId(NULL),
mCouponId(NULL),

Thanks.;

   
Avatar of Hugh McCurdy
Hugh McCurdy
Flag of United States of America image

Two commands  which I'll attach as "code" so fixed spacing will be used.

:1,$s/^.* m/m/
:1,$s/;/(NULL),/

Open in new window

Avatar of HonorGod
The

:1,$

could be replaced by

%
%s/^\([ ^I]*\)[^ ]* \([^;]*\);\1\2(NULL),/

Where the ^I 9 characters in is actually a tab.
This will do it in one expression and allow and preserve indenting.
ASKER CERTIFIED SOLUTION
Avatar of Harisha M G
Harisha M G
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The above works this way:
%s     - Search all lines
/ - delimiter
.* - find anything
\s\+ - followed by at least one space
\(\S*\) - and then a word not containing space, which is group 1 (\1)
;  - followed by a semi-colon
/ - delimiter
\1 - group 1
(NULL), - text, verbatim
/ - delimiter

And if you want to preserve the indentation:

%s     - Search all lines
/ - delimiter
^ - from beginning of line
\(\s*\) - find the spaces and call it group 1 (\1)
.* - then anything
\s\+ - followed by at least one space
\(\S*\) - then a word and call it group 2 (\2)
; - followed by a semi-colon
/ - delimiter
\1\2 - group 1, group2
(NULL), - text, verbatim

%s/^\(\s*\).*\s\+\(\S*\);/\1\2(NULL),/

Open in new window

Avatar of oliversk
oliversk

ASKER

Just what I was looking for.