Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find string except first number

Tags:

regex

vim

I have large file with many information

939112 how is build on floor 3 63044 2022-01-17 13:23:25.891139
939113 how is build on floor 1 63044 2022-01-17 13:23:25.891139
939114 how is build on floor 2 63044 2022-01-17 13:23:25.891139

I want to remove all other things but first number using regex on vim? how can I do it. I can search all digits numbers and remove them, but I want to keep digits and only remove after those digits string.

s/^\d*//g

I am expecting output

939112, 939113, 939114

or

939112
939113
939114
like image 973
shahidkamal Avatar asked Oct 23 '25 00:10

shahidkamal


1 Answers

Let's see what's wrong with :s/^\d*//g

  • It only applies to the current line. You need to give it a :help :range for it to apply to multiple lines. Assuming you want it done on every line in the buffer, the range should be %:

    :%s/^\d*//g
    
  • Since you literally want to operate on the first number in the line, the /g modifier, which means "all matches on the line", is useless and can be removed:

    :%s/^\d*//
    
  • The pattern ^\d* means "zero or more digits, anchored to the beginning of the line" so the command substitutes every number at the beginning of the line with nothing, effectively deleting them… which is the exact opposite of what you want. What you need is a way to separate what you want to keep from what you want to remove.

    ^\d* is good enough for what you want to keep. What you want to remove is everything that comes after it, which can be expressed as .*:

    :%s/^\d*.*//
    

    But this removes everything, you still need to separate them and there are a few ways to do that with Vim's regex dialect.

    The simplest is to use :help \zs:

    :%s/^\d*\zs.*//
    

    With that method, you tell Vim to match what you want to keep and what you want to remove but to only perform the substitution on what you want to remove.

like image 152
romainl Avatar answered Oct 24 '25 21:10

romainl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!