Search code examples
linuxbashfile-rename

How to identify modified file names in a directory?


I have the following four files in a directory:

TRAILBLAZER_107-10016_FTP_SCR_CT_CTAC
TRAILBLAZER_107-10016_FTP_SCR_CT_Recon
TRAILBLAZER_107-10016_FTP_SCR_PET_NAC
TRAILBLAZER_107-10016_FTP_SCR_PET_AC_Frames

And i've made a simple for loop to go through each of those files and change the name of the file based off a certain key word in the name. This essentially just changes the name of the bottom two files:

for file in TRAILBLAZER*
   do
      mv "$file" "${file/PET_AC/PET_TESTAC}"
      mv "$file" "${file/PET_NAC/TESTNAC}"
   done

How would I be able to echo the number of files that have been altered by that for loop, and the number of files in the directory that remain unchanged?


Solution

  • The Parameter Expansion (with substring replacement) does not return any value to let you know if it succeeded or failed. You will need to do that manually. Save the filename before you modify it and check if the file exists afterwards. If it doesn't, a change was made so increment a counter.

    You could do something similar to:

    changed=0                                      ## counter
    
    for file in TRAILBLAZER*
    do
        fname="$file"                              ## save original file name
        
        mv "$file" "${file/PET_AC/PET_TESTAC}"
        mv "$file" "${file/PET_NAC/TESTNAC}"
        
        [ -f "$fname" ] || ((changed++))           ## original exists or increment counter
    done
    
    printf "files changed: %s\n", "$changed"