How can I create a batch file that removes specific characters from the filenames only? Is it possible to do in a script? I'm looking to remove these symbols:
({[}])+-
Let me introduce you to Ruby, a scripting language far more powerful and easier to learn than the M$ alternative Powershell. The windows interpreter you can find at http://rubyinstaller.org/
I could give you the code in one line but for clarity here a 4 line program that does what you need.
Dir['c:/temp/*.package'].each do |file|
new_name = File.basename(file.gsub(/[({\[}\])+-]/, ''))
File.rename(file, new_name)
end
Let me explain, the Dir command enumerates the path with wildcards inside, in unix notation with slashes instead of backslashes and for each file it generates a new_name by taking the basename (filename only) of the path and using a Regular Expression to replace (gsub) the characters inside the /[]/ with the second parameter, '' (empty string). Regular Expressions are the way to go for such things, plenty of information to google if you want to know more about.
Finally I use the utility class File (yes Ruby is totally Object Oriented) to rename the file to the new name.
You could do this with any language but I bet not so concise and readable as in Ruby. Install the Ruby interpreter, save these lines in eg cleanup.rb, change the path to yours and fire it up with ruby cleanup, or just cleanup if your extension is correctly associated.
This renames
c:\temp\na({[}])+-me.package
to
c:\temp\name.package
And as a bonus: here the one line version that does the same in the current folder.
Dir['*'].each {|f| File.rename(f, File.basename(f.gsub(/[({\[}\])+-]/, '')))}
The Windows cmd.exe command shell's rename command lacks the power to do what you need. It can be done with the PowerShell Rename-Item command using the -Replace operator with a regular expression.
However running PowerShell scripts is restricted by security policies, so it is not quite as straightforward as a cmd batch script. A scripting language such as Python may be less problematic.
The Output
C:\Users\User>(
Set FName=test()[]{}+-
Set FName=!Fname:(=!
Set FName=!Fname:)=!
Set FName=!Fname:{=!
Set FName=!Fname:}=!
Set FName=!Fname:[=!
Set FName=!Fname:]=!
Set FName=!Fname:+=!
Set FName=!Fname:-=!
Echo Ren test()[]{}+-.asc !Fname!.*
)
Ren test()[]{}+-.asc test.*
The batchfile
SetLocal EnableDelayedExpansion
for %%A in (*.asc) Do (
Set FName=%%~nA
Set FName=!Fname:^(=!
Set FName=!Fname:^)=!
Set FName=!Fname:{=!
Set FName=!Fname:}=!
Set FName=!Fname:[=!
Set FName=!Fname:]=!
Set FName=!Fname:+=!
Set FName=!Fname:-=!
Echo Ren %%A !Fname!.*
)
Related
All files are in a directory (over 500 000 files), named in the following pattern
AR00001_1
AR00001_2
AR00001_3
AR00002_1
AR00002_2
AR00002_3
I need a script, can be both batch or unix shell that takes everything with AR00001 and moves it into a new folder that will be called AR00001, and does the same for AR00002 files etc
Here's what I've been trying to figure out until now
for f in *_*; do
DIR="$( echo ${f%.*} | tr '_' '/')"
mkdir -p "./$DIR"
mv "$f" "$DIR"
done
Thanks
// Update
Ran this in the CMD
for %F in (c:\test\*) do (md "d:\destination\%~nF"&move "%F" "d:\destination\%~nF\") >nul
Seems to be almost what I wanted, except that it does not take the first 7 characters as a substring but instead creates a folder for each file :/ I'm trying to mix it with your solutions
#echo off
setlocal enabledelayedexpansion
for %%a in (???????_*) do (
set "x=%%a"
set "x=!x:~0,7!"
md "!x!" >nul
move "!x!*" "!x!\" 2>nul
)
for every matching file do:
- get the first 7 characters
- create a folder with that name (ignore error message, if exist)
- move all files that start with those 7 characters (ignore errormessages, if files doesn't exist (already moved))
The following achieves the desired effect and checks for non-existence of the target directory each time before creating it.
#echo off
setlocal ENABLEDELAYEDEXPANSION
set "TOBASE=c:\target\"
set "MATCHFILESPEC=AR*"
for %%F in ("%MATCHFILESPEC%") do (
set "FILENAME=%%~nF"
set "TOFOLDER=%TOBASE%!FILENAME:~0,7!"
if not exist "!TOFOLDER!\" md "!TOFOLDER!"
move "%%F" "!TOFOLDER!" >nul
)
endlocal
In the move command, by moving only the current file rather than including a wildcard, we ensure that we're not eating up file names that might be about to appear the next time around the loop. Keeping it simple, assuming that efficiency is not of prime importance.
I'd recommend prototyping by creating batch files (with a .bat or .cmd extension) rather than trying to do complex tasks interactively using on one-liners. The behaviour can be different and there are more things you can do in a batch file, such as using setlocal to turn on delayed expansion of variables. It's also just a pain writing for loops using the %F interactively, only to have to remember to convert all those to %%F, %%~nF, etc. when pasting into a batch file for posterity.
One word of caution: with 500,000 files in the folder, and all of the files having very similar prefixes, if your file system has 8.3 directory naming turned on (which is often the default) it is possible to run into problems using wildcards. This happens as the 8.3 namespace gets more and more busy and there are fewer and fewer options for ways the file name can be encoded in 8 characters. (The hash table fills up and starts overflowing into unexpected file names).
One solution is to turn that feature off on the server but that may have severe implications for any legacy applications. To see what the file looks like in 8.3 naming scheme, you can do, e.g.:
dir /x /p AR*
... which might give you something like (where the left hand name is the one converted to 8.3):
ARB900~1.TST AR15467_RW322.tst
AR85E3~1.TST AR15468_RW322.tst
ARDDFE~1.TST AR15469_RW322.tst
AR1547~1.TST AR15470_RW322.tst
AR1547~2.TST AR15471_RW322.tst
...
In this example, since the first two characters seem to be maintained, there should be no conflict.
So for example if I say for %a in (AR8*) do #echo %a I get what might at first seem to be incorrect:
AR15468_RW322.tst
AR18565_RW322.tst
AR20376_RW322.tst
AR14569_RW322.tst
AR17278_RW322.tst
...
But this is actually correct; it is all the files that match AR8* in both the long file name and short file name formats.
Edit: I am aware in retrospect that this solution looks very similar to Stephan's, and I had browsed through the existing answers before starting work on my own, so I should credit him. I will try and save face by pointing out a benefit of Stephan's solution. Its use of wildcards should circumvent any 8.3 naming issue: by specifying the wildcard as ???????_*, it only catches the long file names and won't match any of the converted 8.3 file names (all of which are devoid of underscores in that position). Similarly, a wildcard such as AR?????_* would do the same.
With bash, you'd write:
for f in *; do
[[ -d $f ]] && continue # skip existing directories
prefix=${f:0:7} # substring of first 7 characters
mkdir -p "$prefix" # create the directory if it does not exist
mv "$f" "$prefix" # and move the file
done
For the substring expansion, see https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion -- this is probably the bit you're missing.
SOLVED!
Update: It figures moments after posting for help which is something I never do I'd figure it out...I tend to over think things, and that was the case here, it was just so simple! >.<
Solution:
(This worked under Windows 7 Ultimate 64 Bit)
Set var=
Set var=SomeText %var1% %var2% %var3%
Echo %var% > output.txt
See an explanation in my answer below.
I've been searching and trying several posts here similar to my question for hours with no success. I'm not new to Programming in BATCH but I have memory problems and thus can't always remember things. It also doesn't help that I program in other languages on other platforms which usually means I'm trying to use *nix shell commands in my Windows Batch scripts >.<
I've gotten quite close with some examples but nothing that works as needed.
Ideally, I'd like this work to work on Windows 7, 8, 8.1, Vista and 10 as that is the intended target.
This is what I need to accomplish:
The user will answer a series of questions, each question is stored into a .txt file (or variable if you prefer. I just used text files because of a past project where I ran into issues with variables that couldn't be solved and text files worked). The lines in each text file will need to be output into a single text file, on a single line which will then be read back in as a variable and run. Again, you could just use and combine the variables in your example if that's easier for you or both of us ;P
This is a snippet example of how I was doing it
SET file1=
SET /P file1=file1:%=%
ECHO %file1% > file1.txt
Then
copy /b file1.txt + file2.txt + file3.txt + file4.txt output.txt
Here is how I'd like the result to look
toolkit /S "C:\ToolKit Bravo\Data\etc" "D:\ToolKit Bravo\Data\Ops"
The "" quotation marks are necessary. The output MUST be EXACTLY as shown above for the example I've given. The "/S" & paths are variable NOT fixed!
Here is the best I've been able to come up with using variables..
"toolkit /S "C:\ToolKit Bravo\Data\etc" "D:\ToolKit Bravo\Data\Ops""
Update 2 - An explanation as requested:
The paths in the above example directly above this are not fixed! This was an Example Only. "toolkit" is fixed, this doesn't change. "/S" is an option selected by the user to pass on to the "toolkit". Both the source and destination paths are again input by the user in "quotation" marks. They're not fixed paths.
As you can see the result is surrounded by quotations which is NOT acceptable. And Please remember, I NEED the quotations around the paths in the end result, so removing them all is NOT an option!
Any help is greatly appreciated! Thank you for your time.
Just take all of the characters between the quotes.
SET X="toolkit /S "C:\ToolKit Bravo\Data\etc" "D:\ToolKit Bravo\Data\Ops""
ECHO %X%
SET Y=%x:~1,-1%
ECHO %Y%
Solution:
This solved my problem under Windows 7 Ultimate 64 Bit
Set var=
Set var=SomeText %var1% %var2% %var3%
Echo %var% > textfile.txt
Using the SET command I first made sure the variable or var for short was empty. Using this command:
Set var=
I then proceeded to create my variable using all of the other variables I had created and wanted to combine using this line of code:
Set var=SomeText %var1% %var2% %var3%
Note that I have preceded the variables with "SomeText". This is where I'll place the name of the .exe I'm passing the arguments to, but it can be anything you want included. I also need spaces between each variable so I've left spaces between them in the example code. If you don't want the spaces simply remove them, and you'll have 1234, instead of 1 2 3 4.
Finally I send the combined variable out to a .txt file.
Echo %var% > textfile.txt
However, you could also simply call the new variable now like this:
%var%
This kind of question has been asked a few times before on here and I have tried to use the answers in previous posts for my problem but I'm still struggling.
I have in a directory with 100's of files along the lines of
ab00123456.stp
ab00123457.stp
ab00123458.stp
...and so on
I would like to rename all these by adding a pre and post text to the file name.
So the end result would be...
CDE_AB00123456_A.stp
CDE_AB00123457_A.stp
CDE_AB00123458_A.stp
...and so on
(Note the upper and lowercase text change also......as if this wasn't difficult enough already!)
Any clues would be much appreciated.....along the lines of some DOS command perhaps....
Andy
for /? is extremely helpful. In particular, it contains the following substitutions:
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
Thus, you create a for loop that iterates through your files with iteration variable %I and renames %I to CDE_%~nI_A%~xI.
Ready-to-use example:
for %i in (*) DO echo rename %i CDE_%~ni_A%~xi
Try this in a directory of your choice, fine-tune it and remove the echo once you are satisfied.
Note that translation to upper-case is much harder, but since Windows is not case sensitive anyway, I'd just double-check if this is really required.
You should write a batch script to do this. But if you don't know how to script there are 100's of free file renaming tools.
here is a list of some
http://listoffreeware.com/list-of-best-free-file-rename-software/
For example I have the file sample.txt. This file contains:
1111101
2222203
3333303
44444A1
55555A1
66666A1
Now, I want to replace user defined specific pattern. For example I have other file where use defines what he want to replace with. Example the file name is replace.txt. This file contains 2 Columns, first column for the pattern and the 2nd column for the text to be replace.
Example:
replace.txt
2222203 2222203ADD
55555A1 55555A1SUB
Now, when the batch file has been executed, I would like the file sample.txt to have a contents like this:
1111101
2222203ADD
3333303
44444A1
55555A1SUB
66666A1
Also is it possible to have a "space" as part of the text to be replace(column 2?
You may use FindRepl.bat program that is a Batch-JScript hybrid application that perform these replacements in a very efficient way via regular expressions; it uses JScript language that is standard in all Windows versions from XP on. In the basic use of FindRepl.bat you redirect the input file to it and place two strings as parameters, a "search" string and a "replacement" string. For example:
< sample.txt FindRepl.bat "2222203" "2222203ADD"
Previous command will replace all 2222203 strings in the file by 2222203ADD. In order to perform the replacement of several strings, you may include several alternatives in both the search and replacement strings separated by a pipe character (this is called alternation), and include the /A switch to select this feature; for example:
< sample.txt FindRepl.bat "2222203|55555A1" /A "2222203ADD|55555A1SUB"
If you want to define the set of replacements in a separated file, you just need to load the strings from the file, assemble the alternations in two variables and use they in FindRepl preceded by an equal-sign to indicate that they are variables, not literal strings. If you want that the strings may have spaces, then you must use a different character to separate the search and replace parts in the file. For example, if you use a colon in replace.txt file this way:
2222203:2222203 ADD
55555A1:55555A1 SUB
Then the Batch file below solve your problem:
#echo off
setlocal EnableDelayedExpansion
set "search="
set "replace="
for /F "tokens=1,2 delims=:" %%a in (replace.txt) do (
set "search=!search!|%%a"
set "replace=!replace!|%%b"
)
set "search=!search:~1!"
set "replace=!replace:~1!"
< sample.txt FindRepl.bat =search /A =replace
You may download FindRepl.bat and review an explanation of its use from this site; you must place it in the same folder of previous program or, better yet, in a folder included in PATH variable.
I'm working on a Windows batch file that will bcp three text files into SQL Server. If something goes wrong in production, I want to be able to override the file names. So I'm thinking of doing something like this.
bcp.exe MyDB..MyTable1 in %1 -SMyServer -T -c -m0
bcp.exe MyDB..MyTable2 in %2 -SMyServer -T -c -m0
bcp.exe MyDB..MyTable3 in %3 -SMyServer -T -c -m0
I would like to be able to enter default names for all three files, to be used if the positional parameters are not supplied. The idea would be either to execute
myjob.bat
with no parameters, and have it use the defaults, or execute
myjob.bat "c:\myfile1" "c:\myfile2" "c:\myfile3"
and have it use those files. I haven't been able to figure out how to tell if %1, %2 and %3 exist and/or are null. I also don't know how to set those values conditionally. Is this possible? Any suggestions would be appreciated.
To test for the existence of a command line paramater, use empty brackets:
IF [%1]==[] echo Value Missing
or
IF [%1] EQU [] echo Value Missing
The SS64 page on IF will help you here. Under "Does %1 exist?".
You can't set a positional parameter, so what you should do is do something like
SET MYVAR=%1
You can then re-set MYVAR based on its contents.
The right thing would be to use a "if defined" statement, which is used to test for the existence of a variable. For example:
IF DEFINED somevariable echo Value exists
In this particular case, the negative form should be used:
IF NOT DEFINED somevariable echo Value missing
PS: the variable name should be used without "%" caracters.
Both answers given are correct, but I do mine a little different. You might want to consider a couple things...
Start the batch with:
SetLocal
and end it with
EndLocal
This will keep all your 'SETs" to be only valid during the current session, and will not leave vars left around named like "FileName1" or any other variables you set during the run, that could interfere with the next run of the batch file. So, you can do something like:
IF "%1"=="" SET FileName1=c:\file1.txt
The other trick is if you only provide 1, or 2 parameters, use the SHIFT command to move them, so the one you are looking for is ALWAYS at %1...
For example, process the first parameter, shift them, and then do it again. This way, you are not hard-coding %1, %2, %3, etc...
The Windows batch processor is much more powerful than people give it credit for.. I've done some crazy stuff with it, including calculating yesterday's date, even across month and year boundaries including Leap Year, and localization, etc.
If you really want to get creative, you can call functions in the batch processor... But that's really for a different discussion... :)
Oh, and don't name your batch files .bat either.. They are .cmd's now.. heh..
Hope this helps.
rem set defaults:
set filename1="c:\file1.txt"
set filename2="c:\file2.txt"
set filename3="c:\file3.txt"
rem set parameters:
IF NOT "a%1"=="a" (set filename1="%1")
IF NOT "a%2"=="a" (set filename2="%2")
IF NOT "a%3"=="a" (set filename1="%3")
echo %filename1%, %filename2%, %filename3%
Be careful with quotation characters though, you may or may not need them in your variables.
Late answer, but currently the accepted one is at least suboptimal.
Using quotes is ALWAYS better than using any other characters to enclose %1.
Because when %1 contains spaces or special characters like &, the IF [%1] == simply stops with a syntax error.
But for the case that %1 contains quotes, like in myBatch.bat "my file.txt", a simple IF "%1" == "" would fail.
But as you can't know if quotes are used or not, there is the syntax %~1, this removes enclosing quotes when necessary.
Therefore, the code should look like
set "file1=%~1"
IF "%~1"=="" set "file1=default file"
type "%file1%" --- always enclose your variables in quotes
If you have to handle stranger and nastier arguments like myBatch.bat "This & will "^&crash
Then take a look at SO:How to receive even the strangest command line parameters?