vi and sed questions

Kyle Grieser yuf at mentor.cc.purdue.edu
Sun Sep 10 05:38:29 AEST 1989


In article <4370002 at hpavla.HP.COM> rowland at hpavla.HP.COM (Fred Rowland) writes:
>
>vi question
>
>	lastname firstname middlename @address@ ...
>
>	can be changed to
>
>	firstname middlename lastname @address@ ...
>
>	by this key mapping:
>
>	:map ` 0dwf$P(CTRL-V)(Return)
>
>	Just start at line 1, hold ` down, and watch the fun.
>	But there ought to be a better way.

Yeah, there is.  You could just use a global search and replace that
does this for you.  Now, the problem is that these can sometimes be tough
to write for widely varying lines.  I guess you could map it to a key
if you wanted to.  But the following regular expression is a simple example
of how to switch things in a line.  But when you write it, remember that
it always matches the *longest* possible match.  Pretty ugly but it should
work.

	:%s/^\([^ ]*\) \([^ ]*\) \([^ ]*\) \(.*\)$/\2 \3 \1 \4/g

For an explanation of these regular expressions, the ex section of your
Unix manual should do.  But quickly, it means that it will search for the
first 3 words that don't have spaces in them, then anything that follows
them.  Now, the "\(" and "\)" mean that it will remember what it found
so that you can use it in the replacement string.  The first one it finds
will be "\1", the second "\2", etc.  Now you just put them back in the
order you wish.

Hope this helps, and that I didn't forget anything...:-)

-----
Kyle Grieser, Purdue University Computing Center
yuf at mentor.cc.purdue.edu, mentor.cc.purdue.edu!yuf



More information about the Comp.unix.wizards mailing list