I would like to change file with name like:


where I want to insert _FOO in between first _A[0-9]\+ and _B[0-9] so the file names becomes


But my regular expression doesnot work:

for f in $(ls); do mv $f \`echo $f | sed -e s/\(.*_A[0-9]\+\)\(_B[0-9].*\)/$1_FOO$2/\`; done

I tried with a single string:

echo abcd_A90_B2.txt | sed -e s/\(.*_A[0-9]\+\)\(_B[0-9].*\)/$1_FOO$2/

OK: this worked:

echo abcd_A90_B2.txt | sed -e 's/\(_A[0-9]\+\)\(_B[0-9]\)/\1_FOO\2/'
  • Your posting would be greatly improved with better formatting. Here's a help page on how to format. I'd edit it myself, but there's another edit pending so I can't.
    – Tom Zych
    Nov 14 '15 at 12:09
  • Add the -r option to sed (to get it to use extended regular expressions; it normally doesn't understand +).

  • Put your sed script into quotes (preferably single quotes).

  • Change $1 and $2 in your script to \1 and \2:

    sed -re 's/(._A[0-9]+)(_B[0-9].)/\1_FOO\2/'


  • For clarity, you might want to change `…` to $(…) — see this, this, and this — i.e., handle the echo | sed the same way you handle the ls.
  • It’s better to say for f in * (rather than for f in $(ls)).
  • You should quote shell variable references (e.g., echo "$f") unless you have a good reason not to, and you’re sure you know what you’re doing.
  • I have tried but didn't work: echo abcd_A90_B2.txt | sed -e 's/(._A[0-9]+)(_B[0-9].)/$1_FOO$2/' that didn't change abcd_A90_B2.txt Nov 14 '15 at 5:06
  • OK, I revised my answer.
    – Scott
    Nov 14 '15 at 5:14
  • Thanks for this!! Apr 2 '20 at 12:10

You can avoid using sed and other string manipulation by using mmv:

$ mmv -m -n  '*_A*_B*.txt' '#1_A#2_FOO_B#3.txt'
abcd_A90_B2.txt -> abcd_A90_FOO_B2.txt
d1-a2_A1_B1.txt -> d1-a2_A1_FOO_B1.txt

(Leave out the -n or replace it with -v to actually rename the files once you've confirmed all files are matched and renamed as you want.


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.