I have a file in VIM with a bunch of names on separate lines.
I want to open this file with filtered results (easier to view). BUT, I want to preserve the other lines/names.
Example:
#open names file only show names that begin with a
vim names.txt | grep “a.*”
I know the above won’t work but hypothetically speaking if it were to open with the desired functionality (displaying only names starting with a) and I then made changes to those name, and finally saved the file.
I would like to open the file normally without grep and see the rest of the names unaffected.
What I tried…
cat names.txt | grep “a.*” > names.txt
Unfortunately this does not work because it will overwrite the current names.txt file once i run :wq in vim.
Any and all help / suggestions are appreciated
Clarifying the use case The intention is to take each name in a file filter it with a specific pattern. Make changes to those matches and then save the file. So I want to edit all the names that match “^ab”. I’ll make a change to the name. The reason for filtering is for visuals but also to more easily apply macros. Also some tasks are easier since VIM does not support non-continuous highlighting.
The file will have changes - those names that matched the pattern for the filter. But, I want those names that were not matches to remain original.
Your actual use case is not super clear.
If the file is already loaded in Vim, you can do :g/foo
to list the lines matching your pattern at the bottom of the screen until you press a key.
Another method consists in putting the content of the file in a new buffer and then filtering it:
:vnew | r# | v/foo/d
which should leave you with two windows, one with the original file and one with the filtered lines.
If your shell supports process substitution, you can do:
$ vim <(grep foo filename)
where the output of grep foo filename
is presented to Vim as a "file".
Simply use :help :vimgrep
and :help quickfix
:
:vimgrep foo | cwindow
You can tell Vim to use the content of a "file" to build a quickfix list with the -q
flag and execute an arbitrary command afterward with the +
flag:
$ vim -q <(grep -nH foo filename) +cwindow
See :help -q
and :help -+c
.