-1

I need to rename files in a directory taking out a string of characters that is different with each file but starts the same way. I know how to strip characters from the filename, but how do I preserve the extension? I know it's a variation of a common question but I can't find a answer that fits my exact need.

Redshirts_ep6_dSBHpCsvQ3BfQ7-NNIjXYO4pnHpNMvu7bfvURLF3BSzB_3YOOrBBoNnICTR-hg.mp3
-> Redshirts.mp3
PathsNotTaken_ep6_XWixFER4PJyeozVfcxT96UajpnVI7cRMRhAU4Aj9-rpeacnBleuGY9zCPDe0aQ.mp3
-> PathsNotTaken.mp3
that other guy
  • 116,971
  • 11
  • 170
  • 194

1 Answers1

0

The linux command rename is super helpful here. It can use regex to perform the renaming.

This can probably rewritten a bit, but it appears do to the job here:

rename -n 's/(^[^_]*)_.*/$1.mp3/' *.mp3

Just remove that -n flag to run for for real. Leaving it on is just a test.

This regex says:

Characters at the start of the line ^ that don't contain an underscore [^_] repeated any number of times * are captured into a capture group (^[^_]*) if they are followed by an underscore and any number of any other characters _.*. These are then rewritten by using that first capture group $1 followed by .mp3

JNevill
  • 46,980
  • 4
  • 38
  • 63