25

suppose i have the following in a text file (or dired buffer) open in emacs: file_01.txt file_02.txt ... file_99.txt

I want to query-replace or replace the files to 01_file.txt, etc.

I want to use query-replace-regexp or replace-regexp, but don't know what to put in. The search part i put in "file_..", but the ".." are read as periods in the replacement string. I'm beginning to learn regexp and don't know how to do this. Please help, thanks.

1 Answer 1

41

M-x replace-regexp invokes the function to replace with regular expressions.

For Replace regexp enter: \(file\)_\([0-9]+\)

This will create two groups, one that matches the 'file' part, and one that matches the number. The braces \( ... \) are necessary to make the match available later in the replacement string.

For Replace with enter: \2_\1

This inserts the second match from the search string (the numeric part), adds the _ (underscore) and then adds the first match from the search string (the 'file').

For more information on Emacs' regular expressions, see Regexp Syntax and Regexp Replace.

Once you have mastered the regexp basics you might want to check out the Emacs ReBuilder tool with M-x re-builder, which lets you build regexes interactively.

Sign up to request clarification or add additional context in comments.

1 Comment

Super helpful example here. I find it very inconsistent in Emacs regexp that you have to escape round parentheses to make them become a capture group, otherwise they match as parenthesis, but for square brackets you have to escape them if you want them to match as square brackets, otherwise they group terms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.