4

I'd like to write content of the file into separate files each for each line.

For example:

Lorem 
ipsum
dolor
sit
amet
consectetur
adipiscing
elit

I'd like to write 1st line into line1.txt, 2nd into line2.txt, etc.

I've tried this command:

:. w line1.txt

which works for the current line, however this doesn't work:

:. w line\=line('.').txt

even though it would save only a single line.

How can I write a file for each line dynamically based on the current line number?

9

Try a global command:

:g/^/exe ".w! line".line('.').".txt"
  • :g/^/ Do a command for every line (you can adjust this regular expression if you only want to save certain lines, i.e. . for non-empty lines)
  • exe "" execute the following command
  • .w! save the current line and overwrite if already exists. (Remove ! if you don't want to auto-overwrite everything)
  • "line".line('.').".txt" dynamically insert the line number.

See :h :g and :h execute for more info.

  • 1
    Note: this will skip empty lines. use '^' to really match every line. – Christian Brabandt Jul 15 '16 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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