2

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 "$file" "${screen-/file}"
done

fails to change anything. Grateful for an idea where I'm going wrong.

Community
  • 1
  • 1
geotheory
  • 22,624
  • 29
  • 119
  • 196

2 Answers2

3

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
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
1

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.
David W.
  • 105,218
  • 39
  • 216
  • 337