Issue
I have some files in a directory and I want to rename them in such a way they will have sequence.
Customer_Branch_Record.20230303.1349.DAT
Customer_Branch_Record.20230303.1356.DAT
Customer_Branch_Record.20230303.1527.DAT
I want to put a sequence 01 02 03 and so on in between the filenames and output below
Customer_Branch_Record.01.20230303.1349.DAT
Customer_Branch_Record.02.20230303.1356.DAT
Customer_Branch_Record.03.20230303.1527.DAT
I tried Bash to rename but it can only rename into a new name and does not use the original details
#!/bin/bash
a=1
for i in Cust*; do
new=$(printf "Customer_Document_Advices.%02d.txt" "$a") #04 pad to length of 2
mv -i -- "$i" "$new"
let a=a+1
done
OUTPUT:
Customer_Document_Advices.02.txt
Customer_Document_Advices.01.txt
Customer_Document_Advices.03.txt
I want to do this in such a way that I can place a sequence in the middle and still retain the original details of the filename.
Solution
You can try;
a=1
while read -r line; do
echo mv $line $(sed -E "/(\.[^.]*){4,}/ ! s/[^.]*/&.$a/" <<< $line)
let a+=1
done < <(find /path/to/directory -type f -name 'Cust*' -printf '%f\n')
If the output is as expected, remove the echo to persist the changes
Answered By - HatLess Answer Checked By - Marie Seifert (WPSolving Admin)