Solved

Remove special characters from multiple files batch script solution works on everything but '~'

Posted on 2010-09-21
6
2,754 Views
Last Modified: 2012-05-10
We have a client who needs to rename thousands of files in order to upload them to SharePoint and many of those files contain tildes(~).

I have used the script suggested in the related question to replace many different characters in a filename, but it doesn't work on tildes even if it is preceded by a ^ to make it a literal.

Here's the script from the other response.  I modified it to allow a second parameter to pass in the desired character to replace.  Whether I use a parameter or the literal ^~, it doesn't work:

@echo off
 
setlocal ENABLEDELAYEDEXPANSION


if "%~1"=="" (
      echo # ERROR - supply the directory from which to begin the search for
      echo           filenames containing the ampersand symbol.  Any file
      echo           encountered with have the ampersand replaced by 'and'.
      goto :EOF
)
 
if not exist "%~1" (
      echo # ERROR - directory NOT found
      echo          = '%~1'
      goto :EOF
)
 
echo/
echo + Parsing "%~1", please wait ...
 
for /f "tokens=*" %%F in ('dir "%~1" /s/b') do (
      set fileNAME=%%F
      set newFILEname=!fileNAME:^%2= !
      if not "!newFILEname!"=="!fileNAME!" (
            for /f "tokens=*" %%N in ("!newFILENAME!") do (
                  echo   + renaming "!fileNAME!" to "!newFILEname!"
                  ren "!fileNAME!" "%%~nxN"
                  if not errorlevel 1 (
                        echo     - SUCCESS
                  ) else (
                        echo     # FAILED to rename "!fileNAME!"
                  )
            )
      )
)
 
echo - COMPLETE
0
Comment
Question by:cpgtechsupport
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 14

Expert Comment

by:sungenwang
ID: 33726738
Not sure why it doesn't work with '~' in batch command. If you are willing to try running vbscript it is very simple to do. I have included the code to do it:

1. Copy the code into notepad
2. Change line 1, 2, and 3 to appropriate value (set it to a 'test' path first!)
3. Save the change to a file with a "vbs" extension.
4. Double-click the file to run it.

You can change the first 3 lines to replace different symbols. Beware as this code will also change files in sub-folders! Remove line 19-21 if you don't need that.

sew

strFolderName = "C:\temp"
strCharToFind = "~"
strCharToReplaceWith = "_tilda_"

Set objFSO = CreateObject("Scripting.FileSystemObject")

Call TraverseFolder(strFolderName)

Sub TraverseFolder(strFolderName)
	Set objCurrentFolder = objFSO.GetFolder(strFolderName)

	For Each objFile In objCurrentFolder.Files
		If InStr(objFile.name, strCharToFind) > 0 Then
			strNewName = Replace(objFile.name, strCharToFind, strCharToReplaceWith)
			objFSO.MoveFile objFile.ParentFolder & "\" & objFile.name, objFile.ParentFolder & "\" & strNewName
		End If
	Next

	For Each objFolder In objCurrentFolder.subFolders
		Call TraverseFolder(objFolder.ParentFolder & "\" & objFolder.name)
	Next
End Sub

msgbox "done"

Open in new window

0
 
LVL 21

Expert Comment

by:AmazingTech
ID: 33728068
Instead of replacing the tilda with a space how about just removing the tilda?


@echo off
 
setlocal ENABLEDELAYEDEXPANSION


if "%~1"=="" (
      echo # ERROR - supply the directory from which to begin the search for
      echo           filenames containing the ampersand symbol.  Any file
      echo           encountered with have the ampersand replaced by 'and'.
      goto :EOF
)
 
if not exist "%~1" (
      echo # ERROR - directory NOT found
      echo          = '%~1'
      goto :EOF
)
 
echo/
echo + Parsing "%~1", please wait ...
 
for /f "tokens=*" %%F in ('dir "%~1" /s/b') do (
      echo %%F | find "%2"
      if not errorlevel 1 (
          for /f "tokens=1,2,3,4,5,6,7 delims=%2" %%G in ('echo %%~nxF') do (
              set newFILEname=%%G%%H%%I%%J%%K%%L%%M
              echo   + renaming "%%F" to "!newFILEname!"
              ren "%%F" "!newFILEname!"
              if not errorlevel 1 (
                  echo     - SUCCESS
              ) else (
                  echo     # FAILED to rename "!fileNAME!"
              )
          )
      )

)
 
echo - COMPLETE

Open in new window

0
 
LVL 54

Expert Comment

by:Bill Prew
ID: 33728324
Here's a quick example of a way you can remove the unwanted ~ characters from a string in batch.

~bp
@echo off
set Test=Foo~Bar~Rest
echo [%Test%]
for /F "tokens=1-10* delims=~" %%A in ("%Test%") do set Test=%%A%%B%%C%%D%%E%%F%%G%%H%%I%%J
echo [%Test%]

Open in new window

0
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 
LVL 2

Expert Comment

by:misterlupo
ID: 33732573
If you don't mind to use a 3rd party application try tr.exe from the GNU utilities for Win32  to remove unwanted characters from the stream.

C:\>set test=One~Two*Three-Four
C:\>echo %test%|tr -d "~"
OneTwo*Three-Four

C:\>echo %test%|tr -d "~*-"
OneTwoThreeFour



0
 
LVL 5

Expert Comment

by:MAdS
ID: 33795659
Replace  
set newFILEname=!fileNAME:^%2= !
by
set newFILEname=%fileNAME:^%2= %
And you can pass only ~ as parameter (^~ is not necessary, but doesn't hurt either).

 
0
 
LVL 1

Accepted Solution

by:
cpgtechsupport earned 0 total points
ID: 33931534
Hi, thanks for the help all.  We ended up resolving the issue using the FileRenamer application.
0

Featured Post

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
import cert into user machine root store via group policy 3 79
Coding yesterday's date 3 52
how to count files? 4 85
Find computer name from username 9 126
VALIDATING DATES One method of validating dates is to jam the date into the DATE command and see if it accepts it by examining the system's errorlevel value. A non-zero result indicates failure. A typical example might look something like the fol…
This article was inspired by a question here at Experts Exchange (http://www.experts-exchange.com/Software/Photos_Graphics/Images_and_Photos/Q_28629170.html). The requirements stated in that question are (1) reduce the file size of a large number of…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
Suggested Courses

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question