Batch renaming files in OSX terminal

后端 未结 2 486
慢半拍i
慢半拍i 2021-01-23 01:34

I\'m trying to rename files e.g. screen-0001.tif to 0001.tif using the approach in this SO question:

for file in *.tif
do
  echo mv \"$         


        
相关标签:
2条回答
  • 2021-01-23 01:54

    Two things:

    1. You're echoing the commands and not actually executing them. I will do this when I do massive renames just to make sure that the command works correctly. I can redirect the output to a file, and then use that file as a shell script.
    2. The substitution is wrong. There are two ways:
      1. Left most filter ${file#screen-}.
      2. Substitution: ${file/screen/}

    The name of the environment variable always goes first. Then the pattern type, then the pattern

    Here's how I would do this:

    $ for file in *.tif
    > do
    >   echo "mv '$file' '${file#screen-}'"
    > done | tee mymove.sh   # Build a shell script 
    $ vi mymove.sh           # Examine the shell script and make sure everything is correct
    $ bash mymove.sh         # If all is good, execute the shell script.
    
    0 讨论(0)
  • 2021-01-23 01:59

    The easier, IMHO, way to do this is using Perl's rename script. Here I am using it with --dry-run so it just tells you what it would do, rather than actually doing anything. You would just remove --dry-run if/when you are happy with the command:

    rename --dry-run 's/screen-//' *tif
    
    'screen-001.tif' would be renamed to '001.tif'
    'screen-002.tif' would be renamed to '002.tif'
    'screen-003.tif' would be renamed to '003.tif'
    'screen-004.tif' would be renamed to '004.tif'
    

    It has the added benefit that it will not overwrite any files that happen to come out to the same name. So, if you had files:

    screen-001.tif
    0screen-01.tif
    

    And you did this, you would get:

    rename 's/screen-//' *tif
    'screen-001.tif' not renamed: '001.tif' already exists
    

    rename is easily installed using Homebrew, using:

    brew install rename
    
    0 讨论(0)
提交回复
热议问题