Bash – How to Rename Multiple Files Keeping Only Numbers

bashfilenamesrenameshell

I want to rename files like:

SL Benfica vs. SC Beira-Mar 136.mp4
SL Benfica vs. SC Beira-Mar 137.mp4
SL Benfica vs. SC Beira-Mar 138.mp4
SL Benfica vs. SC Beira-Mar Jogo 074.mp4
SL Benfica vs. SC Beira-Mar Jogo 082.mp4
SL Benfica vs. SC Beira-Mar Jogo 112.mp4

But this

for f in *.mp4; do echo mv "$f" "${f//[^0-9]/}.mp4"; done

Adds a "4" at the end:

1364.mp4
1374.mp4
1384.mp4
0744.mp4
0824.mp4
1124.mp4

I think that it gets confused with the "4" in "mp4". How can I solve this?

Best Answer

Remove the .mp4 suffix before you do the replacement.

for f in *.mp4; do
  fname=${f%.mp4}
  mv -- "$f" "${fname//[^0-9]}.mp4"
done

I added -- in case your filenames start with a - and removed the echo. Be careful.

Related Question