Vim - How to read a range of lines from a file into the current buffer

I want to read the line n1-> n2 from the file foo.c into the current buffer.

I tried: 147,227r /path/to/foo/foo.c

But I get: "E16: Invalid range", although I'm sure foo.c contains more than 1000 lines.

+46
vim
Oct 27 '08 at 15:12
source share
7 answers
 :r! sed -n 147,227p /path/to/foo/foo.c 
+71
Oct 27 '08 at 15:19
source share

You can do this in pure Vimscript without using an external tool such as sed:

 :put =readfile('/path/to/foo/foo.c')[146:226] 

Note that we must reduce one of the line numbers, because arrays start at 0 and line numbers start at 1.

Disadvantages: this solution is 7 characters longer than the accepted answer, and it will temporarily consume memory relative to the size of another file.

+19
Jan 22 '14 at 8:24
source share

{range} refers to the destination in the current file, not the range of lines in the source file.

After some experimentation, it seems

 :147,227r /path/to/foo/foo.c 

means to insert the contents of /path/to/foo/foo.c after line 227 into this file. that is, he ignores 147.

+17
Oct. 27 '08 at 15:16
source share

You will need:

 :r /path/to/foo/foo.c :d 228,$ :d 1,146 

Three steps, but it will be done ...

+2
Oct 27 '08 at 15:23
source share

Range allows you to apply a command to a group of lines in the current buffer.

Thus, the range of the read instruction means where to insert the contents into the current file, but not the range of the file you want to read.

+2
Jun 18 '13 at 9:56 on
source share

I just had to do this in my code project and did it like this:

In the buffer with /path/to/foo/foo.c open:

 :147,227w export.txt 

In the buffer, I work with:

 :r export.txt 

Much simpler in my book ... This requires both files to be open, but if I import a set of lines, I usually open them anyway. This method is more general and easier to remember for me, especially if I try to export / import a more complex set of strings using g/<search_criteria/:.w >> export.txt or some other more complicated way of selecting strings.

+1
Jan 15 '14 at 6:13
source share

Other published solutions are great for certain line numbers. It often happens that you want to read above or below another file. In this case, reading the output of the head or tail is very fast. For example -

 :r !head -20 xyz.xml 

Will read the first 20 lines from xyz.xml to the current buffer, where the cursor

 :r !tail -10 xyz.xml 

Will read the last 10 lines from xyz.xml into the current buffer, where the cursor

Head and tail commands are extremely fast, so combining them can be much faster than other approaches for very large files.

 :r !head -700030 xyz.xml| tail -30 

Will read line numbers from 700000 to 700030 from the xyz.xml file to the current buffer

This operation should complete instantly, even for fairly large files.

+1
Jul 10 '17 at 11:55
source share



All Articles