Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:

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

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


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
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

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

Your Answer


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.