Question: Let's say I have opened many files on Vim with `vim file1 file2 file3`... And their content is like the following:

file1:

```
random content
random content
stringThatMatchesRegex
random content

```

file2:

```
random content
random content
random content

```

file3:

```
stringThatMatchesRegex
random content
random content
random content

```

Considering I could have `n` files opened like that, I'd like to find a way of closing all files that match `stringThatMatchesRegex`, so I'd like to close undesirable files with a regular expresssion. In this example, only `file2` would remain open. I know I could close single files using `:bd` on Vim, but I have no idea how to implement this `if` condition. Is it possible? Can I close files that have a line or lines that match a regular expression?

Answer: 
One way is to populate the quickfix list with matches then use `:cfdo` to execute `:bdelete`

```
:vimgrep /pat/ ##
:cfdo bdelete

```

Even though the files are closed the files are still in the argument-list. Remove them via `:argdelete` with `%` to represent the current file

```
:vimgrep /pat/ ##
:cfdo argdelete % | bdelete

```

Additionally, I think it might be worth looking into `:Cfilter` and the quickfix list to do a series of manipulations. Use `:cdo`/`:cfdo` to run commands on the given buffers. Use `:cnext`/`:cprev`/`:cnfile`/`:cpfile` to navigate between files. Filter with `:Cfilter`

```
:cexpr argv()
:packadd cfilter
:Cfilter! /pat/

```

If you are going to be cycling buffers by hand I would suggest some mappings for `:next`/`:prev`. It would also be good to have mappings for the quickfix list. I use Tim Pope's [vim-unimpaired](https://github.com/tpope/vim-unimpaired). Here are some example mappings:

```
nnoremap [A :first<cr>
nnoremap [a :prev<cr>
nnoremap ]a :next<cr>
nnoremap ]A :last<cr>
nnoremap [Q :cfirst<cr>
nnoremap [q :cprev<cr>
nnoremap [<c-q> :cpfile<cr>
nnoremap ]<c-q> :cnfile<cr>
nnoremap ]q :cnext<cr>
nnoremap ]Q :clast<cr>

```

For more help see:

```
:h :vimgrep
:h :grep
:h :cfdo
:h :bdelete
:h :_##
:h :argdelete
:h :_%
:h :cnfile
:h :cexpr
:h argv()
:h :Cfilter
:h :packadd

```
In tab view it is generally easy to see open tabs. Please open files in tabs:

```
'vim -p <file list>'

```

Run regex and commands as:

```
:tabdo g:stringThatMatchesRegex: | q

```

Same can be done with :cfdo instead of (bd) buffer deletion you need to close the file using (q)

```
:cfdo g:stringThatMatchesRegex: | q

```