0

I have a file, with a lot of instances of

...
fclose(f1);
fclose(f2);
fclose(f3);
...

I'd like to replace these with

...
if(fclose(f1)!=0) return 1;
if(fclose(f2)!=0) return 1;
if(fclose(f3)!=0) return 1;
...

But, other than doing two separate search-and-replace, i haven't found a way to do this, which preserves the argument. I think the regex version of search-and-replace may be able to do this, but I'm not nearly proficient at regexes to know how.

  • Just use a keyboard macro? – Drew Nov 7 '18 at 18:41
4

You are correct in that query-replace-regex (Ctrl+Meta+%) can do this. For the regular expression, you want \(fclose(f.)\); and your "to-string" you want if(\1!=0) return 1;

In the regular expression we create a group with \( and \). That group consists of fclose(f.). The . represents "any character".

The "to-string" contains \1 This is a backreference to the first (only in this case) group, and on output is replaced by that match.

You can find more information on regular expressions in the GNU Emacs Manual, the GNU Emacs Lisp Reference Manual, and on the EmacsWiki.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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