1

I am writing a shell script, which can rename all the files in the folder,

We need to search for a particular pattern of files every 30 seconds.

Files in the below format need to be selected,

    core.3467
    core.1234
    core.acde

and they need to be updated as below,

    c.o.r.e.3467
    c.o.r.e.1234
    c.o.r.e.acde

once they are updated an alert email has to be sent that file core.3467 has been changed to c.o.r.e.3467

This is what i have written until now, rename command doesn't seem to work though,

#!/bin/bash
#go the designated directory
cd "<dir_name>"
mail="abc@xyz.com"
#writing all the files in the specified format
ls core* > current.txt
a='cat current.txt'

#renaming the file
rename "s/core/c.o.r.e."*

#writing updated file names
ls c.o.r.e* > updated.txt
b='cat updated.txt'

#sending alert email
mail -s "Files $a changed to $b" $mail
1
  • Be careful, there's two incompatible tools by the name of rename. (Also, I don't think a and b will contain what you think, you need $(cat ...) I think? Jul 10 '15 at 19:02
0
#!/bin/bash

email_address=me@my.domain.com

for file in $(ls /my/directory/name/core*)
do
  newname=$(echo ${file}|sed -e "1,1s/core/c.o.r.e/")
  mv ${file} ${newname}
  echo "File Renamed..."|mail -s "File ${file} renamed to ${newname} ${email_address}
done

This should do...

2
  • This workes fine. But in case i need single email for all the files renamed at a point, how should i change this script? Jul 10 '15 at 21:40
  • In case if there are no files i am getting an error "No such file or directory" >> how to handle this error??? Jul 10 '15 at 22:24
0

Giving all due credit to MelBuslan's excellent scriptlet, let me tweak it to address the request for one single e-mail:

#!/bin/bash

email_address=me@my.domain.com

if test -n "$(find /my/directory/name -maxdepth 1 -name 'core*' -print -quit)" ; then
    for file in $(ls /my/directory/name/core*)
    do
      newname=$(echo ${file}|sed -e "1,1s/core/c.o.r.e/")
      mv ${file} ${newname}
      echo "File ${file} renamed to ${newname}" >> updated.txt
    done
    cat updated.txt | mail -s "Files renamed" ${email_address}
    rm updated.txt
fi
3
  • Updated to also include dealing with the case where there's a non-existent file
    – Michael C
    Jul 10 '15 at 23:05
  • @micheal : it is giving me an error in line 5: saying too many arguments. I tried to put the path in quotes which cleared the error but it just doesnt work. The files are not getting updated. Jul 13 '15 at 20:14
  • UPDATE That is correct; I've updated my code to remove the "too many arguments flaw" using a different if clause. It should work now. Also see stackoverflow.com/questions/6363441/…
    – Michael C
    Jul 15 '15 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.