Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 would like to batch rename files (*.txt) by inserting a number of the format 'RXR1234567' (RXR+7digits) [if such number (and ideally only one) is found in the text] at the front of the filename, e.g. instead of


the file should be called


Could this be done from the command line (grep, rename)? The files are in various subdirectories.

Your thoughts will be appreciated (as always).

share|improve this question
up vote 1 down vote accepted

Try this in the root directory:

find -name '*.txt' -exec sh -c 'PREFIX=`grep -m 1 -oe "RXR[0-9]\{7\}" "$0"` && mv "$0" "${0%/*}/${PREFIX}_${0##*/}"' {} \;

Note: If a file contains multiple matches of the pattern the first one will be used.

share|improve this answer
I'm a bit apprehensive to do the mv right away... I've done PATTERN='RXR[0-9]\{7\}' but would like to first see what happens: grep $PATTERN *.txt is OK, but: grep $PATTERN *.txt -exec sh -c 'grep $PATTERN "$0$"' {} \; just produces lines like '<filename>:0' – ajo Oct 2 '10 at 21:52
... typo above: I DID do "$0" and not "$0$" – ajo Oct 2 '10 at 21:58
I thought that PATTERN was known before as plain text and not as regex. I've edited the answer, now it should do what you want (see the note). Anyway you can test the effects of that command by substituting mv ... with echo mv .. and removing > /dev/null. If something is unclear just ask! – cYrus Oct 3 '10 at 0:51
find -name '.txt' -exec sh -c 'PREFIX=grep -m 1 -oe "RXR[0-9]\{7\}" "$0" && echo ${PREFIX}' {} \; - this makes me see all the RXR results (I'm impressed!); I'll try the rest in a minute – ajo Oct 3 '10 at 2:45
unfortunately, the second part doesn't seem to work?! (the files seem unchanged). What does ${0%/*} mean (?directory), and ${0##*/} (?filename)? - Actually, the subdirectories are not essential, if I could get it working in a single directory that would already be great... – ajo Oct 3 '10 at 2:51

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.