Bash script to remove 'x' amount of characters the end of multiple filenames in a directory?

bash, linux, sed, unix

Solution

 mv $filname $(echo $filename | sed -e 's/.....\.moc1$//');

or

 echo ${filename%%?????.moc1}.moc1

%% is a bash internal operator...

Problem

I have a list of file names in a directory (`/path/to/local`). I would like to remove a certain number of characters from all of those filenames. Example filenames: ``` iso1111_plane001_00321.moc1 iso1111_plane002_00321.moc1 iso2222_plane001_00123.moc1 ``` In every filename I wish to remove the last 5 characters before the file extension. For example: ``` iso1111_plane001_.moc1 iso1111_plane002_.moc1 iso2222_plane001_.moc1 ``` I believe this can be done using `sed`, but I cannot determine the exact coding. Something like... ``` for filename in /path/to/local/*.moc1; do mv $filname $(echo $filename | sed -e 's/.....^//'); done ``` ...but that does not work. Sorry if I butchered the `sed` options, I do not have much experience with it.

Original source