changing a ! to a \nC where \n is a newline

Liam R. E. Quin lee at sq.sq.com
Sat Sep 22 11:12:41 AEST 1990


[this is a vi question, so I've redirected followup thingies to comp.editors]

Sean Sheridan Coleman X5672 (coleman at cam.nist.gov)  writes:
> I am trying to use the global substitution power in vi to 
> replace e;ery occurrence of ! with a newline and a C (\nC)

Vi doesn't understand \n as notation for a newline, but you can
use control-V followed by control-M.

>I have tried the following things:
>g/;/s//\\nC/g   places the string \\nC where the ; is, not a newline.
>g/;/s//\nC/g -- places a nC where the ; is.

Well, these change ; rather than !.  Assuming this is what you mean,
	:g/;/s//^M/g
will do what you want, where ^M is obtained by typing control-V and
then control-M.

If you are in ex instead, (e.g. if you typed ^\ or Q within vi), you
can do
	g/;/s//\
	/g
because ex understands \<newline> to be the same as vi's ^M.

>How about the reverse, replace a newline with a character?

This example will join any line containing "boy" to the one after it,
replacing the newline with the word "whip".

g/boy/s/$/whip/g\
j

You can give a long list of commads after a global, as long as there is a
backslash at the end of each.  (I don't think this works in vi).
So the j will be done on each line matching the pattern, just after the
substitute.

Another common thing to want to do is to get rid of spurious^M
control-M characters at the end of the line (as here),^M
and you can do this by
	:%s/^M$//
where ^M is obtained as above with two keystrokes, control-V control-M.

You cannot include a newline in a pattern, so you can never do
	:%s/boy^Mgirl/girl^Mboy/
for example, to turn
	boy
	girl
into
	girl
	boy
You must use awk or sed, or write a macro, or... well.
Even ex won't let you do that.

Lee

-- 
Liam R. E. Quin,  lee at sq.com, SoftQuad Inc., Toronto, +1 (416) 963-8337
[Granny weatherwax] was opposed to books on strict moral grounds, since she
had heard that many of them were written by dead people  and therefore it
stood to reason reading them would be as bad as necromancy.  [Equal Rites 118]



More information about the Comp.unix.shell mailing list