Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am using gedit regex plugin (Python style regex). I would like to do some arithmetic operation on a backreference to a group.

For example:

PART 1 DATA MODELS Chapter  
2 Entity-Relationship Model 27

I would like to change it to be

PART 1 DATA MODELS Chapter  25
2 Entity-Relationship Model 27

My regex is ^(PART.*)\n(.*\s(\d+))\n, and I would like to replace it with \1 \3-2\n\2\n. But the replacing regex is not right.

share|improve this question
    
See the Python re documentation for the syntax of the regular expressions. The replacement text syntax is also documented there; the only escapes there are to call up a group from the input. –  Gilles Jul 20 '11 at 17:04
    
@Gilles: Thanks! I took a look at the links, but still cannot find a solution. –  Tim Jul 26 '11 at 3:05
add comment

2 Answers

I don't now about gedit, but in vim Arithmetic operations in regex are easy. for example:

:%s/\d\+/\=submatch(0)+25/g

finds every integer and adds 25 to it.

Also, see here a Perl solution to a similar problem.

share|improve this answer
    
I'm not sure what you want to do, so I answered the question in your title. –  Philomath Jul 20 '11 at 8:50
1  
And emacs. Both it and vim are mentioned in this SuperUser Q/A ... For emacs it is: \. in the replacement param, followed by a lisp expression using the backrefernces... –  Peter.O Jul 20 '11 at 11:41
add comment

My understanding is that you want to add at the end of each line beginning by 'PART' the last number of the next line minus 2. If so, it can be done with 'awk':

awk '!/^PART/{print}/^PART/{
getline next_line;
match(next_line, "[^ ]*$");
print $0 " " substr(next_line, RSTART) - 2;
print next_line}' <your file>

This script runs under the assumption that the last line of the input file will not begin by 'PART', and that the line following a line beginning by 'PART' will contain a space and a number at its end. If needed, error checking could be added.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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