Aqui está minha análise, usando bash
, awk
e mv
.
Se olharmos para o nome do arquivo do ponto de vista do awk, filename é apenas uma string com campos separados por espaço, e de interesse particular é o campo $ 3 que tem que ser preenchido com zeros. O roteiro abaixo faz exatamente isso. Certifique-se de colocar o script e executá-lo no mesmo diretório que os arquivos que deseja renomear. Além disso, verifique se ele é executável com chmod 755 renamerScript.sh
Demo
testdir:$ ls
Aaaa.bb - 125 tag tag_tag 9tag Aaaa.bb - 2 tag tag_tag 9tag Aaaa.bb - 4207 tag tag_tag 9tag BACKUP/ renamerScript.sh*
testdir:$ ./renamerScript.sh
mkdir: cannot create directory ‘BACKUP’: File exists
cp: omitting directory ‘BACKUP’
renaming Aaaa.bb - 125 tag tag_tag 9tag to Aaaa.bb - 000125 tag tag_tag 9tag
renaming Aaaa.bb - 2 tag tag_tag 9tag to Aaaa.bb - 000002 tag tag_tag 9tag
renaming Aaaa.bb - 4207 tag tag_tag 9tag to Aaaa.bb - 004207 tag tag_tag 9tag
testdir:$ ls
Aaaa.bb - 000002 tag tag_tag 9tag Aaaa.bb - 000125 tag tag_tag 9tag Aaaa.bb - 004207 tag tag_tag 9tag BACKUP/ renamerScript.sh*
Script
#!/bin/bash
# renamerScript.sh
# Author: Serg Kolo
# Date: Oct 17, 2015
# Purpose : renaming specific files
# Written for: http://askubuntu.com/q/686794/295286
# Make sure you have backup of the files !!!
# comment/uncomment if you do want to do a backup
mkdir BACKUP
cp -t BACKUP *
# This is where the magic happens:
# If we look at filenames from the awk point of view
# "Aaaa.bb - 2 tag tag_tag 9tag" are all really
# space-separated fields. Field #3 is the one we need to edit.
# What we can do is pad it with zeros and then chop off 6
# characters from the end, and store that as new filename
# The rest is just doing mv command from old filename to new
# And also making sure we're operating on files , not directories
# and not renaming the script file,too
for FILENAME in * ;
do
if [ -f "$FILENAME" -a "$FILENAME" != "renamerScript.sh" ]; then
OLDFILENAME="$FILENAME"
NEWFILENAME=$(echo "$FILENAME" | awk '{$3="00000"$3; len=(length($3)-5); $3=(substr($3,len)); print }')
printf "renaming $OLDFILENAME to $NEWFILENAME \n"
mv "$OLDFILENAME" "$NEWFILENAME"
fi
done