morepenguins morepenguins - 4 months ago 16
Linux Question

Batch renaming filenames between hyphens using bash

I'm a student and I'm very new to bash, so any help is greatly appreciated!

I'm trying to rename a batch of files that look like this: local_date_1415+6556_0001.txt and local_date_1415+6556_0002.txt.

Example file name: uuw_07052006_1415+6556_0001.txt

I need the "1415+6556" section of each filename to have a 2M in front of it, like "2M1415+6556". About half the files in the folder already have the 2M, so I can't just search for the string and replace.

Is there a way to rename the batch of files using "_" as a delimiter so I could replace all the third sections entirely with the correct string?

I have the rename command on my machine, I'm just not sure how to use it here.

Answer

Using your version of rename:

rename _ %   *_????+*.txt  # replace the first underscore with a percent
rename _ _2M *_????+*.txt  # add 2M after the second underscore
rename % _   *_????+*.txt  # return the first underscore back

Only works if your filenames don't contain %. If they do, pick a different character.

You can also write the loop yourself:

#! /bin/bash
for f in *_????+*.txt ; do
    before=${f%[0-9][0-9][0-9][0-9]+*}
    after=${f#*_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]}
    mv "$f" "$before"2M"$after"
done
Comments