1

Is there a way to do a search and replace where it searches for if a line contains 4 pipes ( | ) anywhere in the line it will delete it?

I'm working with a big csv file and some lines have 4 pipes and some have 3 pipes. I want to separate out all the ones with 4 pipes in them into a separate file.

2 Answers 2

2

A regex-free one-liner which I like better than my previous answer.

:g/|/if count(getline('.'),'|')==4 | delete

On any line matching at least one pipe, then delete lines with exactly 4 pipes.

5
  • Doesn’t this need an endif?
    – D. Ben Knoble
    Nov 9, 2021 at 12:03
  • That's what I thought initially. It wouldn't hurt, but I found that it's not required. Nov 9, 2021 at 14:22
  • cool thanks! works. but instead of deleting how do I separate it to the bottom of the file for editing manually? Nov 9, 2021 at 17:02
  • :g/|/if count(getline('.'),'|')==4 | move $ Nov 9, 2021 at 17:20
  • Where do you find out all the different parameters such as delete move ....??? what is this g command called. Nov 10, 2021 at 16:37
1

I recommend using:

:g/regex/d

There might be better regexes, but this one works.

:g/^[^|]*\(|[^|]*\)\{4}$/d

"   ^               - start of line
"   [^|]*           - non pipe characters
"  \(|[^|]*\)\{4}   - pipe followed by non-pipes exactly 4x
"   $               - end of line

If the file is very big, Vim might take too long to do this. To speed it up, add space and underscore after the command to delete each match to the black hole register.

:g/regex/d _
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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