I have around 7,000 .txt files that have been spat out by a program where the naming convention clearly broke. The only saving grace is that they follow the following structure: id, date, time.
m031060209104704.txt
--> id:m031
date:060209
time:104704
.txt
Sample of other filenames (again same thing):
115-060202105710.txt
--> id:115-
date:060202
time: 105710
.txt
x138051203125338.txt
etc...
9756060201194530.txt
etc..
I want to rename all 7,000 files in this directory to look like the following:
m031060209104704.txt
--> 090206_104704_m031
.txt
i.e date_time_id (each separated by underscores or hyphens, I don't mind). I need the date format to be switched from yymmdd to ddmmyy as shown directly above though!
I'm not clear on whats overkill here, full program script or bash command (MAC OS). Again, I don't mind, any and all help is appreciated.
Try something like:
#!/bin/bash
# directory to store renamed files
newdir="./renamed"
mkdir -p $newdir
for file in *.txt; do
if [[ $file =~ ^(....)([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{6})\.txt$ ]]; then
# extract parameters
id=${BASH_REMATCH[1]}
yy=${BASH_REMATCH[2]}
mm=${BASH_REMATCH[3]}
dd=${BASH_REMATCH[4]}
time=${BASH_REMATCH[5]}
# then rearrange them to new name
newname=${dd}${mm}${yy}_${time}_${id}.txt
# move to new directory
mv "$file" "$newdir/$newname"
fi
done