2

I have filenames in a directory in the format of "APP_ENTITY_part___20120910.txt"

I would like to strip off everything after the 3 underscores and keep the first portion of the filename.

Is there a good website that could direct me in how to accomplish this?

Or, maybe one of you dos batch experts can lead me in how to do this?

Zack Macomber
  • 6,682
  • 14
  • 57
  • 104

3 Answers3

6

There is a very simple solution that uses variable expansion search and replace to inject a REM command.

@echo off
setlocal
for %%F in (*) do call set "var=%%F" & call :procName
exit /b

:procName
::truncate at the 1st occurance of ___
set "var=%var:___="&rem %
::print the result
set var
exit /b

The critical line is set "var=%var:___="&rem %

Suppose var=Part1___Part2

After substitution, the line becomes: set "var=Part1"&rem Part2

The above solution truncates at the first occurance of ___.

A name like Part1___Part2___Part3 will result in Part1.

If you want to truncate at the last occurance of ___ and get a result like Part1__Part2, then the solution is more complicated.

I use search and replace to change ___ to a folder delimiter, then a 2nd FOR with the ~p modifier to strip off the last part, and then search and replace to restore the leading ___ delimiter(s).

@echo off
setlocal disableDelayedExpansion
for %%F in (*) do (
  set "var=%%F"
  setlocal enableDelayedExpansion
  set "var2=!var:___=\!"
  if "!var2!" neq "!var!" for %%A in ("\!var2!") do (
    endlocal
    set "var=%%~pA"
    setlocal enableDelayedExpansion
    set "var=!var:~1,-1!"
    set "var=!var:\=___!"
  )
  echo var=!var!
  endlocal
)
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • In the first example, instead of removing/truncating the rest of the variable after the '___', how would you set that to a second variable? I assume its in the 'set "var=%var:___="&...." I can't work out the correct syntax though. – Impulss Mar 22 '13 at 01:26
1

You can install Cygwin or some alternative (with the proper libraries included, like the "rename" program) and use one of the top two answers from this SO question (pasted below). You may want to test the regular expressions and globs before implementing either of these:

rename 's/___(.*)\.txt/\.txt/' *_part___*.txt

or

for f in *_part___*.txt; do mv $f $(echo $f | sed 's/___(.*)\.txt/\.txt/g'); done

Community
  • 1
  • 1
0

A simple one-line solution for you:

set DirNam=%DirNam:~,-12%

This will work for you if you are always just stripping 4 underscores plus a date ____YYYYMMDD from the end of the name.

Maybe sort out other Directory names by doing this:

setlocal enabledelayedexpansion
for /d %%x in (*____????????) do ( 
  set DirNam=%%x
  set DirNam=!DirNam:~,-12!
  echo %%x is now !DirNam!
)
James K
  • 4,005
  • 4
  • 20
  • 28