1

My file working.txt has 1000's of lines, which repeat in a simple pattern as follows:

name
date_ax
name
date_cd
name
date_ed
name
date_dc
...etc

I need to replace each instance of name with the sequential next line from another file called other.txt, such that each line of other.txt is looped through for each replacement of name.

other.txt file content looks like this:

namedewqdwq
name32321321
name3434243gf
nameewqewqeeq

After the replacement my working text file working.txt would look like this:

namedewqdwq
date_ax
name32321321
date_cd
name3434243gf
date_ed
nameewqewqeeq
date_dc
...etc

How can this be done?

1 Answer 1

2

You can use a list with the entries of the second file and then use remove() in an expression to pop the first item of the list for every match.

For example:

:let replacements = readfile('other.txt')
:%s/^name$/\=remove(replacements, 0)/

See also:

  • readfile(), which reads the contents of the file into a List.
  • :help sub-replace-expression, using \= at the start of the :substitute replacement in order to evaluate a Vimscript expression to determine the contents of the replacement.
1
  • 1
    thanks :) appreciated. That works very well.
    – Kes
    Jun 16, 2021 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.