On Tue, 6 Jun 2006, Gary Johnson wrote:

On 2006-06-06, Salman Mohsin <[EMAIL PROTECTED]> wrote:
Hi,

I have a long list of city names (more than 2,000 of them) in a file, each
name on a separate line. I'd like to modify each line so that:

ABERFOYLE
.
.
ZURICH

Becomes:

cities[0] = "ABERFOYLE"
.
.
cities[2039] = "ZURICH"

Is there a way I could issue a command (or some commands) and achieve the
above?

   :%s/.*/\='cities['.line(".").'] = "'.submatch(0).'"'

The key here is the "\=<expression>" in the replacement string.  See

   :help sub-replace-expression

You can't mix replacement expressions with other forms of
replacement string.  That is, the replacement must start with \= and
everything that follows must be part of that expression.

Using an expression allows the use of functions such as line() to
interpolate the current line number.  "submatch(0)" returns the
entire string matched by the pattern.  See

   :help line()
   :help submatch()

Adding to this, let's say you have ABERFOYLE on line 5, and ZURICH on
line 2044, then this would do what you want:

  :5,2044s/.*/\='cities['.(line(".") - 5).'] = "'.submatch(0).'"'

--
Gerald

Reply via email to