views:

48

answers:

2

I have a folder with files x_blah.blah y_ho.hum z_hi.ho which I just need to drop everything to left of the underscore and the underscore from so I'm left with blah.blah ho.hum hi.ho

+2  A: 

Windows Batch

@echo off

FOR %%i in (PREFIX*.txt) DO (set file=%%i) & CALL :rename
GOTO :eof

:rename
REN "%file%" "%file:~6%"
GOTO :eof

You need to adjust the 6 to the length of the prefix. So for your example, you could do this:

@echo off

FOR %%i in (x_*.txt) DO (set file=%%i) & CALL :rename
GOTO :eof

:rename
REN "%file%" "%file:~2%"
GOTO :eof

Linux

Linux has multiple solutions, one of them would be this:

rename 's/^x_//' *

where x_ is the prefix.

poke
No this is in a batch file with many other things that needs to be ran every minute.
Ah, okay, adjusted the answer.
poke
+1  A: 

This should do the trick:

setlocal enabledelayedexpansion

for %%i in (*_*) do (
   set old_name=%%i
   set new_name=!old_name:*_=!
   move "!old_name!" "!new_name!"
)

For explanation:

  • setlocal enabledelayedexpansion enables the so called delayed variable expansion, a feature that e.g. allows you to dereference variables inside loops
  • for %%i in (*_*) do starts a loop over all file names inside the current directory that at least have one _ and assigns that file name to the loop variable %%i
  • set old_name=%%i assigns the content of the loop variable to a regular variable named old_name
  • set new_name=!old_name:*_=! does some nice string substitution on the content of the variable old_name, replacing all characters before the first _ and the _ itself with nothing. The result is stored in new_name. See the help of the SET command for more details (type help set on the command line).
  • move "!old_name!" "!new_name!" finally is the command issued to rename each file from its old to its new name

Update:

To go through the files in all sub folders you can use the FOR /R variation of the for loop. To start in the current directory, change the loop header to something like:

for /r %%i in (*_*) do (

But you also need to take into account that the loop variable now contains the fully qualified path of the file name, so you also have to change the loop body a bit to only substitute the file name:

for /r %%i in (*_*) do (
   set file_path=%%~dpi
   set old_file_name=%%~nxi
   set new_file_name=!old_file_name:*_=!
   move "!file_path!!old_file_name!" "!file_path!!new_file_name!"
)

Hope that helps.

Frank Bollack
This is what I need, thanks. One more question. I have several folders in the same directory. Is there anything I can add to go through all those folders without having to copy and paste this several times and keep changing directories and hardcoding the folder names?
Using * in string substitution is new to me, Its in set /?, but well buried.
Andy Morris