How do I search in multiple files for 1st line of file matching a pattern?
e.g. I want to search for files starting with ++
++ Heading 1
and not
+ Heading 1
++ Heading 2
Any pointers appreciated.
How do I search in multiple files for 1st line of file matching a pattern?
e.g. I want to search for files starting with ++
++ Heading 1
and not
+ Heading 1
++ Heading 2
Any pointers appreciated.
Use :vimgrep
as below:
:vimgrep /\%(\%<2l\)foo/ *.*
This will search for foo
in all files in the current folders (*.*
) only in the 1st line (<2l
).
Alternatively may search either in the current file (%
), certain files (*.c
) or recursively (**/*.*
, see: :help starstar-wildcard
). See: :help :vimgrep
and :help /\%>l
.
To jump between patterns, use :cn[ext]
and :cp[revious]
. See more at SO.
However there is no straight forward solution to use substitution on quickfix list.
To search and replace pattern for the first line only for multiple-files, you can use Ex command:
$ ex +'bufdo!1s/php/bar/ge' -cxa *.*
Note: The :bufdo
command is not POSIX.
For doing something to multiple files, :argdo
is your friend. You might need to edit the argument list first. It's set to the opened files on vim start, you can output it with :args
and set it with, e.g., :args *.txt
. After that, a simple :argdo /^++
will search for the first line that starts with ++
and puts the cursor there.
That assumes the cursor is on the first line of each buffer. To assure that, use :argdo :normal 1G
first.
Note that you did not specify to do anything special with that line, so I've just performed the search here (search as in "put the cursor there").
Edit: If you wanto to substitute something, just use the usual vim command for argdo, i.e. :argdo %s/^++/--/ge
. Note that for edits you should use :set hidden
, otherwise it won't be able to switch buffers. Use the e
qualifier for the substitution so the command doesn't stop at a buffer with no match.
^++
only when it appears in the first line in the file, not find the first occurrence of a line that matches ^++
.