Finding the line with a specific character before the last character. Suppose, I have the following string

1. addar_ctrl1,1,2,0,0,1
2. addar_ctrl2,3,2,0,1,0
3. addar_ctrl3,4,8,0,0,0
4. addar_ctrl4,2,6,0,1,1

I want to grasp the line contains '1' in the 2nd last position in each row.

Expected output:

2. addar_ctrl2,3,2,0,1,0
4. addar_ctrl4,2,6,0,1,1
  • 1
    do you know regular rexpressions? Commented Nov 27, 2020 at 12:49
  • @ChristianBrabandt Yes, I know, but failed to catch this mach.
    – KittoMi
    Commented Nov 27, 2020 at 13:30

2 Answers 2


Use a negated :global, e.g.:

  • Should I use :g!/,1,[^,]*$/d? I used it and got the expected matched output in separate that contains only the matched lines.
    – KittoMi
    Commented Nov 27, 2020 at 13:28
  • Thank you for your reply :).
    – KittoMi
    Commented Nov 27, 2020 at 13:29
  • 2
    The :g command actually stands for :global, not :grep. While using :g! is of course possible, I see it much more often used as :v (for :vglobal) and I typically recommend using that one (since it's also shorter, easier to type.)
    – filbranden
    Commented Nov 27, 2020 at 14:01
  • @filbranden: noted, thx.
    – Thor
    Commented Nov 27, 2020 at 15:40

This is the one situation where using an external tool such as awk can help, particularly if you're trying to match something on a column in the middle (not close to the start or end), or when the rows don't have the same number of columns, etc. While using a regex to match those is almost always possible, it's often not the most convenient approach.

You can shell out to awk from Vim to filter the buffer and keep only the lines with a 1 in column 5, with:

:%!awk -F, '$5 == 1'

You can also use a more restrictive range (in place of %) if you don't want to filter the whole buffer. Or use a Visual selection, in which case when you press : Vim will automatically fill in :'<,'> which is the range corresponding to the lines in the last Visual selection.

Note that ! is a special character in a :! command in Vim (, it's replaced with the previous external command executed), so you need to escape it if you use it. For example, to use an external awk to filter the contents and keep only lines where the fifth field is not zero, you should use:

:%!awk -F, '$5 \!= 0'

Note the backslash escaping the !, to prevent Vim from expanding it.

  • 1
    Good call @Quasímodo! That's indeed likely to come up when using an external awk and is not obvious to spot... I updated the answer to mention this case. Thank you!
    – filbranden
    Commented Nov 27, 2020 at 19:30

Your Answer

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

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