Bat renames files from different directory

2

I have the following script that works if I run it from the same directory:

@echo off
for %%i in (*.csv) do (set fname=%%~ni) & call :renameFile
goto :eof
:renameFile
ren "%fname%.csv" "%fname:~13,16%.csv"
goto :eof

What I intend is to execute it from another directory. I have a share with several directories

- Orion (unidad de red)
  |-AEMET (directorio)
    |-Scripts (directorio)
    |-Temporal (directorio)

In Temporal I have the files that I have to rename, but to have everything better organized I would like the script to be executed from the directory Scripts .

For this I made the following modification but I can not get it to work.

@echo off
Set "Ficheros=\AEMET\Temporal\*.csv"
for %%i in ("%Ficheros%") do (set fname=%%~ni) & call :renameFile
goto :eof
:renameFile
ren "%fname%.csv" "%fname:~13,16%.csv"
goto :eof

I've tried:

  • Removing the bars from the network drive AEMET\Temporal\
  • Calling it from \Temporal\

But I can not get it to work from another directory.

What am I doing wrong?

    
asked by David 31.10.2017 в 09:08
source

1 answer

2

A possible solution would be to execute your first script, which works without problems, but changing the active directory. So what you would do at the beginning would be to change the active directory to Temporal, search the files, rename them and return to the directory of the Scripts:

@echo off
cd ..\Temporal
for %%i in (*.csv) do (set fname=%%~ni) & call :renameFile
goto :goBack
:renameFile
ren "%fname%.csv" "%fname:~13,16%.csv"
goto :eof
:goBack
cd ..\Scripts

But if you want to go with your second option, I'll tell you what is wrong and how to correct it:

  • In this line Set "Ficheros=\AEMET\Temporal\*.csv" the route is incorrect, you have a \ at the beginning (or add the Orion network name) and therefore the route does not connect to the correct place and you will not find any CSV (or you will not find the ones you want).
  • In the for loop you lose the file path (which was in the Files variable), but now i will only have the name of the file without the path.
  • When using ren by only putting the name of the file, without a path, it will try to rename the CSV files of the current directory, not the Temporary one.

One idea would be to change Ficheros so that instead of the list of files, it contains the path where you want to change the files (moving the selection to the same loop for ) and then use Ficheros again in the ren (only in the first argument).

Then, this code will work for you:

@echo off
Set "Ficheros=..\Temporal\"
for %%i in ("%Ficheros%*.csv") do (set fname=%%~ni) & call :renameFile
goto :eof
:renameFile
ren "%Ficheros%%fname%.csv" "%fname:~13,16%.csv"
goto :eof

You could change the path of Ficheros to be absolute instead of relative and then the script will work for you regardless of where you call it.

    
answered by 31.10.2017 / 14:44
source