Please help with my task:

I have a folder with three sub-folders containing six files each. There are two files in each sub-folder with :nopm in their file names.

I need to create a shell script that checks all the folders and their sub-folders. If there are any file names with :nopm as part of the name, this (:nopm) should be removed from the name. If there is another file with the same name, as in :nopm removed, it should be deleted and every interaction should be logged into a file named log.txt.

For example:

I have a directory: Example_September

In this directory I have three sub-directories:


These three directories have six files each:

fruit      : apple pear     banana  melon   grape :nopmlime
car        : fiat  mercedes ferrari audi   suzuki :nopmaudi
vegetables : bean  broccoli cabbage corn   carrot :nopmgarlic

In the directory fruit the script should rename :nopmlime to lime
In the directory car the script should delete :nopmaudi

All rename and remove must log to a .txt file like:

I remove the file(s)
I rename the file(s)

I should complete the task like this. Can you help to repair this?

for if find /data/irm/Example_September -name :nopm:
do mv filename1 filename2 
echo I rename the file. 
rm file 
echo I remove the file. 
fi >> /data/irm/Example_September/log.txt \;

Description in comments in script:

 # assign log file name into variable
 # iterate over all files in this folder an its subfolders
 for fname in $(find . -type f) 
      # check if current file name contains ":nopm" substring
      there_is_match=$(echo $(basename $fname) | grep ':nopm' | wc -l)
      # if yes value "1" will be assigned into there_is_match variable
      if [ $there_is_match -eq 1  ]  ; then
           # cut off ":nopm" substring - I use perl instead of sed because I find its regex nicer then sed's
           newname=$(echo $fname | perl -p -e 's/:nopm//g')
           # check if file without substring already exists
           if [ -e $newname ] ; then
                # if yes delete it and log it
                rm -f $newname
                echo "Deleted file $newname" >> $log_file_name
           # rename file and log it
           mv $fname $newname
           echo "Renamed file $fname to $newname" >> $log_file_name

Please remember that [ ] brackets are shortcut for bash test command. It can compare numbers, strings and check some conditions on files and dirs.

  • It works!!! I just customize it and im done. Thanks a lot dude! – KisPogesz Sep 23 '15 at 8:35

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.