LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   REGEXP in VIM (https://www.linuxquestions.org/questions/linux-newbie-8/regexp-in-vim-920915/)

john_erlandsson 12-28-2011 12:13 PM

REGEXP in VIM
 
Hi!

I am trying to learn VIM and regular expressions.
Got stuck when trying to add line numbers to a Heidenhain CNC file.

Example:
Before.
Code:

;Not code
#Not code

L X+0.000 Y+0.000 F100 M
C X+10.000 Y-15.000 F M
CP IA+60.000 F M

Now I want to add line numbers to every line that starts with a capital letter.

After.
Code:

;Not code
#Not code

0 L X+0.000 Y+0.000 F100 M
1 C X+10.000 Y-15.000 F M
2 CP IA+60.000 F M

Here is what i thought would work:
Code:

:%s/\(^\)\([A-Z]*\)\2/\=line('.')-1 . ' '
%s - preform substitute on whole file

\(^\) - add "beginning" of the line to first "backreference group"

\([A-Z]*\) - add the rest of a valid line to secound "backreference group"

\2/\=line('.')-1 . ' ' - substitute the first backreference with line number and whitespace


This prints line number on all lines.

I cant figure out how to add the secound backreference as a condition. Like: only preform substitute if \3 exists.


Any help is appreciated.


//John

john_erlandsson 12-28-2011 12:17 PM

This is what i started with:
Code:

:%s/^/\=line('.')-1 . ' '
It gives the same result.

john_erlandsson 12-28-2011 02:58 PM

This is almost correct:
Code:

%g/^[A-Z]/s/^/\=line('.')-1 . ' '
Gives the output:
Code:

;Not code
#Not code

3 L X+0.000 Y+0.000 F100 M
4 C X+10.000 Y-15.000 F M
5 CP IA+60.000 F M
 L X+0.000 F M
7 L X+0.000 Y+0.000 F M

Is it possible to make the line() function count only the lines matched in the first expression?

john_erlandsson 12-29-2011 05:40 AM

I solved it:

Code:

let X=-1|%g/^[A-Z]/let X=X+1|s/^/\=X
Here is how i think it works:

let X=-1 Declare variable X and initialize it to -1

|%g/^[A-Z] Pipe to new command and search entire file for lines that starts with a capital letter

/let X=X+1 Increment the variable X when a match is found...

|s/^/\=X ...and print the number at the beginning of that line


All times are GMT -5. The time now is 09:00 PM.