Computer Hope
Microsoft => Microsoft DOS => Topic started by: one stupid guy on December 30, 2009, 12:41:46 PM
-
I can't figure it out...
I'd like to rename a number of files, replacing underscores with a space.
For example, I'd like to rename "the_first_file.txt" to "the first file.txt"
I thought the following would work, but it didn't:
RENAME *_*>* *" "*.*
Can anyone help a brother out?
-
This might work...
@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir /b') do (
set fileorig=%%a
set filenew=!fileorig:_= !
ren !fileorig! "!filenew!"
)
Save it in the folder which contains the files you want to change.
-
setlocal enabledelayedexpansion
for /f "delims=" %%A in (*.txt) do (
set oldname=%%A
set newname=!oldname:_= !
ren "!oldname!" "!newname!"
)
-
Great minds think alike
-
Why thank you ST, strangest thing, I was just about to say that too.
-
C:\>type under2.bat
@echo off
setlocal enabledelayedexpansion
dir /b the*.txt > _txtfiles.txt
for /f "delims=" %%i in (_txtfiles.txt) do (
echo %%i
set var=%%i
For /F "delims=" %%a in ('echo %%i ^| sed 's/_/ /g') do set var3=%%a
echo var =!var!
echo var3 =!var3!
ren "!var!" "!var3!"
rem ren "!var3!" "!var!"
)
Output:
C:\> under2.bat
the_first_file.txt
the_fourth_file.txt
the_second_file.txt
the_third_file.txt
the_first_file.txt
var =the_first_file.txt
var3 =the first file.txt
the_second_file.txt
var =the_second_file.txt
var3 =the second file.txt
the_third_file.txt
var =the_third_file.txt
var3 =the third file.txt
the_fourth_file.txt
var =the_fourth_file.txt
var3 =the fourth file.txt
C:\>
-
Oh God! he's found about sed now! I shudder to think what's next...
OP: Dear Mr bill... I tried running your script and it said "'sed' is not recognized as an internal or external command,
operable program or batch file."
-
"'sed' is not recognized as an internal or external command,
operable program or batch file."
http://www.computerhope.com/unix/used.htm
ghostdog74 is the expert with sed and awk (gawk)
I'm sure ghostdog74 will help you.
-
Suppose they don't want to use your weird sounding program?
-
Suppose they don't want to use your weird sounding program?
http://www.computerhope.com/unix/used.htm
Sed has been used many times on the Hope Board.
Sed is a quick and easy stream editor
Speak with Ghostdog74.
-
I can't figure it out...
I'd like to rename a number of files, replacing underscores with a space.
For example, I'd like to rename "the_first_file.txt" to "the first file.txt"
I thought the following would work, but it didn't:
RENAME *_*>* *" "*.*
Can anyone help a brother out?
if you have many underscores, eg file_____test.txt, do you want to replace them with just 1 space as well?
-
I better fess-up on my newbieness; I know less than you think.
For the first proposed solution above (thanks to Helpmeh and Salmon Trout), do I just type it into a DOS emulator, or is it more involved?
Keep in mind that I want this to go through a few hundred files and make this change to them all (swap an underscore for a space).
Ghostdog, there are no instances of multiple underscores, but I would want them replaced by a single space.
I tried to identify the elements of the above solution so as to educate myself.
Below is a line-by-line explanation. Is my understanding correct?
setlocal enabledelayedexpansion - the activity of the command will be kept to a specified folder
for /f "delims=" %%A in (*.txt) do - 'for' is like an "IF" command, but I don't know what /f does.
- I don't get the "delims=" either.
- Are the percentage signs are wildcards?
- I know that *.txt means 'all text files'
set oldname=%%A - does this specify the format of the old name?
set newname=!oldname:_= ! - this makes sense (I think), it changes the underscore to a space
ren "!oldname!" "!newname!" - this renames the file, with the new (underscoreless) name
Thank you for your insight and patience,
-
I better fess-up on my newbieness; I know less than you think.
For the first proposed solution above (thanks to Helpmeh and Salmon Trout), do I just type it into a DOS emulator, or is it more involved?
Keep in mind that I want this to go through a few hundred files and make this change to them all (swap an underscore for a space).
Ghostdog, there are no instances of multiple underscores, but I would want them replaced by a single space.
I tried to identify the elements of the above solution so as to educate myself.
Below is a line-by-line explanation. Is my understanding correct?
setlocal enabledelayedexpansion - the activity of the command will be kept to a specified folder
for /f "delims=" %%A in (*.txt) do - 'for' is like an "IF" command, but I don't know what /f does.
- I don't get the "delims=" either.
- Are the percentage signs are wildcards?
- I know that *.txt means 'all text files'
set oldname=%%A - does this specify the format of the old name?
set newname=!oldname:_= ! - this makes sense (I think), it changes the underscore to a space
ren "!oldname!" "!newname!" - this renames the file, with the new (underscoreless) name
Thank you for your insight and patience,
Honestly, you understood very well for a beginner. I'll just confirm and fix what you said about the script:
Setlocal enabledelayedexpansion I'm not exactly sure what this means, but regular variables in for commands are wrapped in ! and not %.
"Delims=" That means that there are no delimiters (things that seperate the information) to be used.
%%a (or %%A) That is a FOR variable. It is only used in the FOR command. For every line of data, it will become that. So if a line was file_name.txt, then %%a would become file_name.txt .
in (*.txt) That is where the data comes from. For each file, there is a new line. * is a wildcard. If you knew how long the desired file is, you can use a certain amount of ? (question marks are a 1-character wildcard).
Set oldfilename=%%a Doing that allows me to work with the name.
Set newfilename=!oldfilename:_= ! That will make newfilename the same as oldfilename, but every _ becomes a space.
Ren !oldfilename! !newfilename! Pretty explanitory.
Understand a little better now?
-
That's about it, helpmeh, but if I can just jump in with the FOR line...
for /f "delims=" %%A in (*.txt) do
The FOR command works like this
FOR [switch] [option block] %%Variable in (dataset) do (something)
You can type FOR /? at the prompt to get several screens full of detailed help but I will briefly break down what that line does
/f ... switch that tells FOR that (dataset) is to be treated as a series of lines to be processed. In this case, dataset is *.txt which means "one by one, each file with the .txt extension in the current directory".
"delims=" ... option block that tells FOR that each line of output is to be taken whole and not split into "tokens"
%%Variable ... A loop variable is a single letter, a-a or A-Z and the contents of (dataset) are assigned one by one to this variable, in this case %%A will contain, one after the other, the name of each .txt file.
-
Ghostdog, there are no instances of multiple underscores, but I would want them replaced by a single space.
You can use vbscript. this replaces multiple _ (and consecutive _ ) with single space.
Set objFS = CreateObject("Scripting.FileSystemObject")
Set regEx = New RegExp ' Create regular expression.
regEx.Global=True
strFolder = WScript.Arguments.Item(0)
strOld = WScript.Arguments.Item(1)
strNew = WScript.Arguments.Item(2)
regEx.Pattern = strOld&"+"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
strFileName = strFile.Name
If objFS.GetExtensionName(strFileName) = "txt" And InStr(strFileName,strOld)>0 Then
strFileName = regEx.Replace(strFileName, strNew)
strFile.Name = strFileName
End If
Next
save as replace.vbs and on command line
c:\test> cscript //nologo replace.vbs c:\test _ " "
-
Thank you for your insight and patience.
Learn Sed ( stream editor ). One simple line of code does it all:
type _txtfiles.txt | sed 's/_/ /g' > newfiles.txt
ref:
http://gnuwin32.sourceforge.net/packages/sed.htm
http://www.computerhope.com/unix/used.htm
http://www.faqs.org/faqs/editor-faq/sed/
-
bill, will you please shut up about sed.
-
Learn Sed ( stream editor ). One simple line of code does it all:
type _txtfiles.txt | sed 's/_/ /g' > newfiles.txt
ref:
http://gnuwin32.sourceforge.net/packages/sed.htm
http://www.computerhope.com/unix/used.htm
http://www.faqs.org/faqs/editor-faq/sed/
that's only part of the story! you need to rename your files....
-
bill, will you please shut up about sed.
be gentle, its the new year :) . Using sed is not wrong. all depends on OP.
-
you're right Ghostdog.
Bill will you please shut up about sed give us several pages full of stuff about sed, maybe, hopefully including what the OP asked for, but not if you don't want to. It's not like this is a "help" forum, after all.
-
Bill, will you please shut up about sed.
Who are You? You are not in charge of anything.
Sed is without a doubt the best solution.
-
I don't see any renaming going on, bill.
-
Ghostdog, there are no instances of multiple underscores, but I would want them replaced by a single space.
Problem solved. No need to argue about using sed or not. The code already posted without sed works perfectly fine so stop fighting. You (the second-person, multiple, you) are just spamming the forums with USELESS posts!
-
I reckon all this kind of stuff probably puts people off coming back. They read their email, see a notification, click the link, read a half baked reply from BillTard, and then go somewhere else. He should be deleted and deleted again every time he comes back.
-
Who are You? You are not in charge of anything.
HE SAID PLEASE!
GAWD!
*storms off*
-
I don't see any renaming going on, Bill.
See post #5 in this thread.
-
See post #5 in this thread.
Way to edit your post with more useless code.
-
Way to edit your post with more useless code.
You are right. There is only one solution and Helpmeh provided the code.
We all learn from Helpmeh.
Helpmeh can earn a great salary in the computer field if he remains in the computer field.
Good luck.
-
Bill, if I was new to this forum I'd think you were about 5 years old.
-
Way to edit your post with more useless code.
I don't think its useless like you said. let's be fair, first, using sed is not wrong. sed IS and CAN be used to change text/strings. What he is doing is on the right track (although there are obstacles in that track). second, why don't we let OP decide which is the best for himself.
lastly, let us enjoy the new year and have peace for 1 day. (at least :) )
-
We've given the working code to the OP, he has used it but questions how it works. We (ST and I) have explained the code and the OP has left. No need to bump a dead topic.
-
Bill, if I was new to this forum I'd think you were about 5 years old.
The correct grammar: "if I were" not "if I was"
Example? What post and statement are you referring to?
Thanks for the kind words.
-
Sorry, I'm not getting involved in your mind games.
-
We've given the working code to the OP, he has used it but questions how it works. We (ST and I) have explained the code and the OP has left. No need to bump a dead topic.
Only the original poster can ever benefit from the code.
-
Only the original poster can ever benefit from the code.
err...
THAT'S THE POINT!
-
The correct grammar: "if I were" not "if I was"
Subjunctive often overlooked these days, esp. in Leftpondia.
-
We've given the working code to the OP, he has used it but questions how it works.
ok, maybe i am blind, but which post was it that he questions the code provided??
We (ST and I) have explained the code and the OP has left. No need to bump a dead topic.
that's not really correct. the way i see it, a topic can be "bumped" IF there are other ways, or better ways to solve the problem. this is a forum remember? There's no way you can dictate Mr A's or Mr B's solution is the one and only. And what do you mean dead topic? This thread is not more than 3 days old...
-
GD74, we're having a whack at Billrich. Whose side are you on?
-
I've considered seeing things from Ol' rich's point of view.
Really, I have.
I struggled for hours.
But no matter what I did...
I simply could not get my head that far... (it goes on, but I'll let your imaginations fill in the missing portion!)
Also, the calendar stating "new years day" doesn't bring back the patience I lost.
-
GD74, we're having a whack at Billrich. Whose side are you on?
lol, ST, i am not siding anyone. just looking at facts as i already mentioned.
Maybe i have missed something, but whatever it is, let's just chill for today ok? Enjoy it as much as we can, and tomorrow is a better day.
-
I never meant to start a little war, I just wanted to rename some files. My thanks to all who provided input. I'm no hippy, but I hope there is peace in 2010, be it here on this forum and worldwide.
Now, back to my original issue. I've been working with the solution provided first (thanks to Salmon Trout and Helpmeh). As I "get" some of the coding, I've been able to follow/understand it a bit better. Yes I want to rename these files, but I also want to learn a skill that I can apply to other situations in the future. The additional elucidation on the meaning of each element of the code has been infinitely useful (please keep it coming).
Still, I'm missing something clearly. I took a three files as a test, and put them into a folder;
File_1_test.txt
File_2_test_.txt
_File_3_test.txt
all now reside in C:/test
In the end, I want the files to be named:
File 1 test.txt
File 2 test.txt
File 3 test.txt
I'm using WinXP, so I used the DOS emulator and navigated to the folder (C:/test). I then typed in the code provided, all in one big long line of input text to the emulator (if I hit enter to mimic the carriage returns in the code provided, it would execute the code only partially or not at all).
i.e., I literally typed in
"setlocal enabledelayedexpansion for /f "delims=" %%A in (*.txt) do (set oldname=%%A set newname=!oldname:_= ! ren "!oldname!" "!newname!")"
Then I hit enter.
It didn't crap out per se, but it didn't actually do anything. The filenames remain unchanged.
Take a second to roll your eyes at my ignorance as needed, then please enlightened me if you're willing and able.
My thanks to all,
-
That is not the way to run the code.
The code that I posted was intended to be used as a "batch file" or "command script". This is a text file which can be executed. It would have a .bat or .cmd extension. Here is how to run it
1. Start Notepad
2. In this page here, highlight the code that follows, click "Edit" in the the menu at the top and choose "Copy".
@echo off
echo Ready to rename files
echo.
pause
echo.
echo Renaming files...
echo.
setlocal enabledelayedexpansion
for /f "delims=" %%A in (*.txt) do (
set oldname=%%A
set newname=!oldname:_= !
echo Renaming !oldname! to !newname!
ren "!oldname!" "!newname!"
)
echo.
echo All done
echo.
pause
3. Click in Notepad, click "edit" and choose "Paste"
4. The code should appear in Notepad. I have dressed it up a bit to make it more friendly.
5. Now, in Notepad, choose File, Save As.. and save it in the folder where the files are that you wish to rename. Call it something with a .bat extension for example MyRename.bat. Don't call it Rename.bat!
6. Open Windows Explorer in the folder where the files are.
7. Double click the icon for the batch file you have just saved.
-
Totally cool. I figured I was missing something painfully obvious.
I appreciate the recipe.
I created the .bat file as directed (I think), placed it in the c:/test directory with the three test files, and I got the following:
"The system cannot find the file *.txt."
What did I miss this time?
-
My mistake!!! Sorry
@echo of
echo Ready to rename files
echo.
pause
echo.
echo Renaming files...
echo.
setlocal enabledelayedexpansion
for /f "delims=" %%A in ( 'dir /b *.txt' ) do (
set oldname=%%A
set newname=!oldname:_= !
echo Renaming !oldname! to !newname!
ren "!oldname!" "!newname!"
)
echo.
echo All done
echo.
pause
-
Call me crazy, but that's really cool. It works, pure and simple.
Many, many thanks.
To further my understanding, what does the switch b do (/b)?
Now, just to be picky, I'd love to have certain [first] letters capitalized.
For example, if the files are currently as below:
file 1 - test one.txt
File 2 - test two.txt
file 3 - test three.txt
I would like:
File 1 - Test one.txt
File 1 - Test two.txt
File 1 - Test three.txt
Please don't waste further time on my trivial problems, but if you have a ready solution I'd happily take it, along with an understanding of how/why it works, so that I can learn.
Again, my gratitude.
-
To further my understanding, what does the switch b do (/b)?
open a command window, and type
dir (ENTER)
and then
dir /b (ENTER) and you'll see the difference.
Type dir /? to see an explanation.
Now, just to be picky, I'd love to have certain [first] letters capitalized.
This is really beyond the capabilities of a batch file, you should be looking at a bulk file rename utility such as Bulk Rename Utility
http://www.bulkrenameutility.co.uk/Main_Intro.php
-
I never could resist a challenge...
@echo off
echo Ready to rename files
echo.
pause
echo.
echo Renaming files...
echo.
setlocal enabledelayedexpansion
for /f "delims=" %%A in ( 'dir /b *.txt' ) do (
set oldname=%%A
set newname=!oldname:_= !
set char1=!newname:~0,1!
set rchars=!newname:~1!
if "!char1!"=="a" set char1=A
if "!char1!"=="b" set char1=B
if "!char1!"=="c" set char1=C
if "!char1!"=="d" set char1=D
if "!char1!"=="e" set char1=E
if "!char1!"=="f" set char1=F
if "!char1!"=="g" set char1=G
if "!char1!"=="h" set char1=H
if "!char1!"=="i" set char1=I
if "!char1!"=="j" set char1=J
if "!char1!"=="k" set char1=K
if "!char1!"=="l" set char1=L
if "!char1!"=="m" set char1=M
if "!char1!"=="n" set char1=N
if "!char1!"=="o" set char1=O
if "!char1!"=="p" set char1=P
if "!char1!"=="q" set char1=Q
if "!char1!"=="r" set char1=R
if "!char1!"=="s" set char1=S
if "!char1!"=="t" set char1=T
if "!char1!"=="u" set char1=U
if "!char1!"=="v" set char1=V
if "!char1!"=="w" set char1=W
if "!char1!"=="x" set char1=X
if "!char1!"=="y" set char1=Y
if "!char1!"=="z" set char1=Z
set newname=!char1!!rchars!
echo Renaming !oldname! to !newname!
ren "!oldname!" "!newname!"
)
echo.
echo All done
echo.
pause
-
luckily the english alphabets only have 26 characters :)
-
luckily the english alphabets only have 26 characters :)
Indeed!
-
I tried it with my example, and couldn't get it to work. It still deals with the underscore properly, and most of the coding made some sense to me (the IF statemetns are intuitive).
My example was:
If the files are currently as below:
file 1 - test one.txt
File 2 - test two.txt
file 3 - test three.txt
I would like:
File 1 - Test one.txt
File 1 - Test two.txt
File 1 - Test three.txt
And I don't get the results I wanted.
So that I 'get it', can you help me understand what these two lines mean:
set char1=!newname:~0,1!
set rchars=!newname:~1!
Specifically, what does the squiggle mean (~), and what does it mean to have the zero and one separated by a comma (~0,1)?
For that matter, what does "rchars" mean? I looked on the ComputerHoper glossary page and couldn't find it.
Thank you again,
-
Well, I named some files according to your description and got these results...
Before
S:\>dir /b *.txt
test_file_002.txt
test_file_003.txt
test_file_001.txt
Run batch
Ready to rename files
Press any key to continue . . .
Renaming files...
Renaming test_file_002.txt to Test file 002.txt
Renaming test_file_003.txt to Test file 003.txt
Renaming test_file_001.txt to Test file 001.txt
All done
Press any key to continue . . .
After
S:\>dir /b *.txt
Test file 002.txt
Test file 003.txt
Test file 001.txt
If the files are currently as below:
file 1 - test one.txt
File 2 - test two.txt
file 3 - test three.txt
I would like:
File 1 - Test one.txt
File 1 - Test two.txt
File 1 - Test three.txt
What's this "File 1" prefix? You never mentioned that before.
set char1=!newname:~0,1!
create a variable called char1 and make it equal to the first character (0 from the start) of newname
set rchars=!newname:~1!
create a variable called rchars and make it equal to the characters from the 2nd (1 from the start) to the end of newname
A colon and "squiggle" is used in string slicing in batch language
!apple:~0,3! means the first 3 characters of the variable named apple
rchars is just a name I made up for the variable.
-
Salmon Trout
It would;d be helpful is somebody would document where you find the definition for the batch file mid string extraction function.
If you try to Google "DOS :~" you won't find it. Instead you are lead to a site about a beer called Dos Equis.
-
use "cmd string manipulation" as a search term. seems to bring up relevant results.
-
It is available from the command prompt by typing SET /? - it's immediately after the section explaining SET /P, but if folks prefer to read it in a browser, this is as good a place as any...
http://www.computerhope.com/sethlp.htm
-
Thank you both.
I have been using DOS for years and never saw that documented.
Just did not know where to find it.
The XX Beer commercial got me side tracked. :D
-
I think It shld a bit long way
correct me if i am wrong
First make list of files by using :
1} dir PLACE UR DIRECTORY HERE\*.txt /b >list.txt
2}edit list.txt with notepad
3}replace "_" with "space" [without quotes]
4}add "ren" be4 every file's name and then the file
for ex
ren the_example.txt the example
save it as BATCH and apply it
-
the_mad_joker,
I like your method.
If you don't know the academic answer...
just use the pragmatic solution.
-
the_mad_joker,
I like your method.
If you don't know the academic answer...
just use the pragmatic solution.
Sounds like a manual method. Use Notepad? This guy is a mad joker.
ST and Helpmeh used an automatic one liner.
-
I think It shld a bit long way
correct me if i am wrong
First make list of files by using :
1} dir PLACE UR DIRECTORY HERE\*.txt /b >list.txt
2}edit list.txt with notepad
3}replace "_" with "space" [without quotes]
4}add "ren" be4 every file's name and then the file
for ex
ren the_example.txt the example
save it as BATCH and apply it
do you know how long that will take? Try doing it with hundreds of files. What about thousands?
-
do you know how long that will take? Try doing it with hundreds of files. What about thousands?
Many editors allow you to do search and replace. If you have column select, copy and paste then the above would take a few seconds.
-
Sounds like a manual method. Use Notepad? This guy is a mad joker.
ST and Helpmeh used an automatic one liner.
So how is an automatic one linerwritten without using a text editor?
Using the text editor to repeat and replace is using a program to automate a task.
Can you write a one liner that does not have to be tested more that once? If not, it is not really a one-liner. It took you two or more attempts to get it right. You had to write the line again and again.
Many power users prefer methods that others can easily understand and modify. Some one liners can do that very well. Some just confuse the average user.
A general rule is to have a solution that can be shown in about 25 lines of well arranged text. And inside normal margins.
-
um... geek... Notepad stays OPEN... none of it's actions are automated, you need to perform the replace from within the notepad GUI...
-
none of it's actions are automated,
My is, I click replace all. That's automation.
Look up automation. 8)
-
My is, I click replace all. That's automation.
Look up automation. 8)
it's only partial automation of the entire task; it replaces all in a single file; it doesn't scale.
-
B C programmer,
That's a good answer. Rather than pursue this any further, let me pick your brain for something I have thought about. It relates to the topic at hand.
In any situation like the one in this topic there are any number of scenarios where you might want to replace or change or rename a file or set of files in a group of directories. Perhaps some users have a need to do this on a regular basis. Now is there a way of making an automated program that will help the user do this without the need for the user to have to rewrite and edit a batch file.? In other words, a script that would be fully automated from the viewpoint of the end-user. To that end, I was wondering if there is a way to invoke notepad and make it do search and replace from a script? If not, would a person have to use one of the GNU utilities such as SED?
-
I believe so, I'm sure there are tools that can perform the replacement directly from the command line, maybe even a batch file could be constructed and called that does that.
-
There are various editors that can be scripted, UltraEdit is one. I gace up using Notepad a very long time ago. Scite is a useful scriptable free editor.
-
B C programmer,
That's a good answer. Rather than pursue this any further, let me pick your brain for something I have thought about. It relates to the topic at hand.
In any situation like the one in this topic there are any number of scenarios where you might want to replace or change or rename a file or set of files in a group of directories. Perhaps some users have a need to do this on a regular basis. Now is there a way of making an automated program that will help the user do this without the need for the user to have to rewrite and edit a batch file.? In other words, a script that would be fully automated from the viewpoint of the end-user. To that end, I was wondering if there is a way to invoke notepad and make it do search and replace from a script? If not, would a person have to use one of the GNU utilities such as SED?
in *nix world long ago, tools such as vi, emacs, sed, awk, ed etc already have the functionality to "change" (or rather edit) files on the command line, because the author of those programs programmed those functionalities into them. If the author of notepad.exe does the same, then yes, you can use notepad,exe to change files on the command line.
notepad.exe /F "word_to_find" myfile #find word
notepad.exe /R "word_to_replace" myfile #find and replace
Just for record, you can also use edlin to "script" editing a file automatically in windows platform.
-
Just for record, you can also use edlin to "script" editing a file automatically in windows platform.
Works better is you make a patch to edlin.
-
Works better is you make a patch to edlin.
if a "patch" is ever going to be made, its definitely not by me or anyone else but the original author. (its not open source). Anyway, editors are just tools that opens a file , do something to it and depending on users, save to new file or not. So any programming language with capability to open/close/edit files are also "editors" in a sense.
You can make a native "sed" using vbscript. eg just for s///
Set objFS=CreateObject("Scripting.FileSystemObject")
Set regEx = New RegExp
Set objArgs = WScript.Arguments
strPattern = objArgs(0)
p = Split(strPattern,"/")
strOld = p(1)
strNew = p(2)
regEx.Pattern = strOld
If p(0) = "s" Then
r = 1 'set replace
Else
r = 0
End If
If p(UBound(p)) = "g" Then
regEx.Global=True 'set global flag
Else
regEx.Global=False
End If
strFile = objArgs(1)
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfLine
If r= 1 Then
strLine = objFile.ReadLine
strLine = regEx.Replace(strLine, strNew)
WScript.Echo strLine
Else
'strLine = regex.Execute(strLine)
WScript.Echo "-->" & strLine
End If
Loop
output
C:\test>more file
old new old
blah
old
C:\test>cscript //nologo sed.vbs "s/old/new/" file
new new old
blah
new
C:\test>cscript //nologo sed.vbs "s/old/new/g" file
new new new
blah
new
C:\test>sed "s/old/new/" file
new new old
blah
new
C:\test>sed "s/old/new/g" file
new new new
blah
new
this way as you keep on adding features, you can create your own "sed" natively :)
-
Thanks to those who made it a great thread by their contributions. I have been searching and reading different posts on the net for the last 2 hours and this is the best forum I found so far on Windows Shell programming.
My problem is half solved by the posts made by "Helpmeh" and "Salmon Trout" on the first page of this thread. The second part of the problem is that how do I execute this piece of code recursively for all subdirectories. I have few hundreds GB of image files that I need to rename and there are hundreds of subdirectories over different backup disks. So, I would appreciate any help.
Thanks,
mushutterclicks
-
The second part of the problem is that how do I execute this piece of code recursively for all subdirectories.
mushutterclicks
C:\>dir /?
Displays a list of files and subdirectories in a directory.
/
/S Displays files in specified directory and all subdirectories.
/
for /f "delims=" %%a in ('dir /b') do (
for /f "delims=" %%a in ('dir /s /b') do (
-
C:\>dir /?
Displays a list of files and subdirectories in a directory.
/
/S Displays files in specified directory and all subdirectories.
/
for /f "delims=" %%a in ('dir /b') do (
for /f "delims=" %%a in ('dir /s /b') do (
Hi Bill,
Thanks for your response. I just tried that and it did not work. I think there is a problem with /S option here as the first /f option in the FOR is going to return only the files. May be I need to call this from another batch file or something to make things easier.
Thanks,
myshutterclicks
-
Please post the code you used. We can modify from there.
The code offered was one line from #1 post in this thread. All of the batch file must be used:
@echo off
setlocal enabledelayedexpansion
rem for /f "delims=" %%a in ('dir /b') do (
for /f "delims=" %%a in ('dir /s /b') do (
set fileorig=%%a
set filenew=!fileorig:_= !
ren !fileorig! "!filenew!"
)
"Save it in the folder which contains the files you want to change. "
Save the above code to a file with .bat extention. For example: namepic.bat. Then type namepic.bat at the command line and press return.
C:\>namepic.bat
-
Just throwing this out there: isn't the /s switch supposed to come after the /b switch?
-
Just throwing this out there: isn't the /s switch supposed to come after the /b switch?
The switches and filespecs for dir can come in any order
dir /b /s *.txt
dir /s /b *.txt
dir *.txt /s /b
dir *.txt /b /s
dir /b *.txt /s
dir /s *.txt /b
are all equivalent
-
Oookkk. I wasn't sure, as I've always used /b /s and have never encountered problems (except when there are way too many files/folders in one folder).
-
Oookkk. I wasn't sure, as I've always used /b /s and have never encountered problems (except when there are way too many files/folders in one folder).
Check them out. I just did.
-
Check them out. I just did.
No I believe you. I believed you when you posted it. Anyway, I can't test the now. iPod Touch, remember?
-
Here is the code with the /s that you suggested and it does not work for some reason.
@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir /s /b *.myname.*') do (
set fileorig=%%a
set filenew=!fileorig:.myname=!
rename !fileorig! !filenew!
)
Without the /s it works for the directory where I run it from. I can double click or run from command line, the result is the same. Also a point to note is that I do not have double quote in the rename command and it works just fine.
I never did any windows/dos shell programming but have basic knowledge of programming.
Thanks,
myshutterclicks.
Please post the code you used. We can modify from there.
The code offered was one line from #1 post in this thread. All of the batch file must be used:
@echo off
setlocal enabledelayedexpansion
rem for /f "delims=" %%a in ('dir /b') do (
for /f "delims=" %%a in ('dir /s /b') do (
set fileorig=%%a
set filenew=!fileorig:_= !
ren !fileorig! "!filenew!"
)
"Save it in the folder which contains the files you want to change. "
Save the above code to a file with .bat extention. For example: namepic.bat. Then type namepic.bat at the command line and press return.
C:\>namepic.bat
-
Since the basic code works for a directory I think the following idea might work. but I don't have the knowledge base to do the programming in shell.
1. Parameterize the basic code, ie. pass the directory path to this script.
2. Make another script to scan through the subdirectories recursively and when a it finds a directory call the first batch file (from point #1) with the directory as parameter.
This code seems to rename files recursively. May be the gurus can tweak it to make it work with the above routine.
For /r %%x in (*.jpg) do ren "%%x" *.jpeg
Notice the /r switch in the FOR clause for scanning the directories recursively.
Thanks,
myshutterclicks
-
For /r %%x in (*.jpg) do ren "%%x" *.jpeg
Notice the /r switch in the FOR clause for scanning the directories recursively.
We have pasted my level of expertise.
Contact Salmon Trout directly.
The two of you can make the this work.
Size and volume of the image files might be part of the problem.
Good luck
bye
-
Hi Bill,
Thanks for your time and thoughts for exploring the dir command with /s option. Hopefully someone will be able to come up with the solution.
Thanks,
myshutterclicks
We have pasted my level of expertise.
Contact Salmon Trout directly.
The two of you can make the this work.
Size and volume of the image files might be part of the problem.
Good luck
bye
-
Size and volume of the image files might be part of the problem.
The DIR command can be very finicky with huge amounts of files/folders in one root.
Does the DIR command stop mid-process and exit (not giving an error message), freeze (also not giving an error message), or just give an error message and not do anything?
The only time I've actually messed up the DIR command (when I typed it in properly) was when there were tens of thousands of folders, within one sub folder (I was trying to see the network drive), although the problem could probably be reproduced with a much less amount.
-
Does the DIR command stop mid-process and exit (not giving an error message), freeze (also not giving an error message), or just give an error message and not do anything?
Good question. There was, at one time, some kind of limit in NT as to how much stuff you can make the command interpreter do in one big gulp.
EDIT: found this
There are more files in the directory than the command interpreter (COMMAND.COM) can sort. The maximum amount of memory that COMMAND.COM can allocate for a DIR operation is 64 kilobytes minus 512 bytes. Each file displayed by the DIR command requires 22 bytes for its entry, making the total number of files that can be displayed in a sorted directory equal to 2295 files [(65536-512)/22].
# Microsoft MS-DOS 6.22 Standard Edition
# Microsoft Windows 95
http://support.microsoft.com/kb/100842
-
Very good find...although this is what happened for me:
It displayed a list of all folders in the root of the drive (about 300 in all), went down one level in the last folder, displayed the contents...eventually displaying over 1000 files/folders. It then encounters a folder I like to call the beast (the one with 20 000+ folders in it). It makes it through a decent way then just sits there. Although it definately goes through more than 1000 (over 2000 if including the ones from the directory levels above).
-
I am testing this with few files only. So no question of having huge number of files.
I get this error with the /s option with just 3 files in one directory and it does not even rename the files under the same directory. It works file without the /s option. But then that's not for recursive.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
Thanks,
myshutterclicks
The DIR command can be very finicky with huge amounts of files/folders in one root.
Does the DIR command stop mid-process and exit (not giving an error message), freeze (also not giving an error message), or just give an error message and not do anything?
The only time I've actually messed up the DIR command (when I typed it in properly) was when there were tens of thousands of folders, within one sub folder (I was trying to see the network drive), although the problem could probably be reproduced with a much less amount.
-
I am testing this with few files only. So no question of having huge number of files.
I get this error with the /s option with just 3 files in one directory and it does not even rename the files under the same directory. It works file without the /s option. But then that's not for recursive.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
Thanks,
myshutterclicks
Can you post all code in your script right now? A syntax error means the switches/etc. were not written properly.
-
Can you post all code in your script right now? A syntax error means the switches/etc. were not written properly.
Here is the code:
---------------------------------------------
@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir /s /b *_MG_*.JPG') do (
set fileorig=%%a
set filenew=!fileorig:_MG_=!
rename !fileorig! "!filenew!"
)
pause
---------------------------------------
I have these files in the directory.
_MG_3338.JPG
_MG_3339.JPG
_MG_3340.JPG
_MG_3341.JPG
------------------------------------------
Here is the error message:
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
Press any key to continue . . .
---------------------------------------------------
The code works just fine without the /s.
Thanks,
myshutterclicks
-
Doing DIR /? gives the list of options.
It states you give the file name first and follow with the switches.
So why not try it the recommended way?
Using a feature that is not given in the documentation is not wise, unless you have a reason for it.
(So you just want to see what happens?)
-
Doing DIR /? gives the list of options.
It states you give the file name first and follow with the switches.
So why not try it the recommended way?
Using a feature that is not given in the documentation is not wise, unless you have a reason for it.
(So you just want to see what happens?)
The result is still the same. I get the same error message.
-
Sorry that did not help.
I am just shooting in the dark. That is why I am the Geek after dark.
You need the /s to get all sub directories. -Right?
Well, just move the DIR thing out of the for loop.
I have been following this third, but get lost in the stuff. Do you really need recursion? Can you just use iteration? Maybe I missed something.
Could you just do DIR *.JPG /B/S >big-list.txt
Then have the for loop precess each line in big-list.txt
That way the for loop does not have to do recursion. I guess.
-
I am not keen on using the recursion at all. I am just looking for a way to rename my files in many directories over many backup disks. In the process of renaming I need to remove/replace some strung from the file name.
I don't need a full blown rbust solution. Just a way to reduce the manula work. The script works for a single directory and it renames the files correctly. Here is an idea a threw earlier today. I am reposting for easy reference.
====================================================
Since the basic code works for a directory I think the following idea might work. but I don't have the knowledge base to do the programming in shell.
1. Parameterize the basic code, ie. pass the directory path to this script.
2. Make another script to scan through the subdirectories recursively and when a it finds a directory call the first batch file (from point #1) with the directory as parameter.
This code seems to rename files recursively. May be the gurus can tweak it to make it work with the above routine.
For /r %%x in (*.jpg) do ren "%%x" *.jpeg
Notice the /r switch in the FOR clause for scanning the directories recursively.
===============================================================
Thanks,
myshutterclicks
Sorry that did not help.
I am just shooting in the dark. That is why I am the Geek after dark.
You need the /s to get all sub directories. -Right?
Well, just move the DIR thing out of the for loop.
I have been following this third, but get lost in the stuff. Do you really need recursion? Can you just use iteration? Maybe I missed something.
Could you just do DIR *.JPG /B/S >big-list.txt
Then have the for loop precess each line in big-list.txt
That way the for loop does not have to do recursion. I guess.
-
Nobody gets any points for astuteness, perspicacity or just plain gumption here! None of you noticed that the OP posted the same number of error messages as there were files. Therefore, the problem was occurring in the loop, not in the FOR line which set it up.
Also, nobody bothered (come on guys!) to type rename /? at the prompt and read the help, whereupon it would have become clear where the problem lies.
Namely in the incorrect syntax being used with the ren / rename command.
The syntax is
RENAME [drive:][path]filename1 filename2
The code was doing this
RENAME [drive:][path]filename1 [drive:][path]filename2
To give a concrete example
This is wrong
Rename "C:\My Documents\My Pictures\My Meals\Cheeseburger105.jpg" "C:\My Documents\My Pictures\My Meals\Hamburger105.jpg"
This is right
Rename "C:\My Documents\My Pictures\My Meals\Cheeseburger105.jpg" "Hamburger105.jpg"
When you have to specify the full path of a file to rename, e.g. because it is not in the current directory, supply it once, before the present (old) filename and then supply just the new name (no path).
It actually says this in the rename /? help
Note that you cannot specify a new drive or path for your destination file.
Dir /s /b always produces a full path for each file, so you need to get at the drive, path, name and extension information using the FOR variable modifiers which you can read about in the FOR /? documentation
Here is some commented code which (I hope) will make all this clear...
@echo off
REM You need this because you are setting variables (and reading them)
REM inside a parenthetical structure (a loop in this case)
setlocal enabledelayedexpansion
REM The /f switch tells FOR to treat the output of the command
REM as a series of text lines to be processed
REM I have changed the variable to upper case to make
REM the variable modification clearer
for /f "delims=" %%A in ('dir /s /b *_MG_*.JPG') do (
REM If %%A is a file path and name (or just a filename)
REM %%~dpA is its drive and path...
set filepath=%%~dpA
REM ... and %%~nxA is its name and extension
REM Thus we have removed the drive and path...
set filenameold=%%~nxA
REM Modify just the name without path
REM to get the new name
set filenamenew=!filenameold:_MG_=!
REM Give the Rename command the full path & old name
REM for the file to be renamed, and just the new name
rename "!filepath!!filenameold!" "!filenamenew!"
)
Since we have now got up to 7 pages, I feel justified in having a moan about how standards are slipping here on CH. Somebody posts a question, somebody else (who shall be nameless) posts a partial solution, the OP tries it out, it doesn't work, and then a whole bunch of people just post guesses. Nobody read the command documentation; nobody tried specimen code.
-
Since we have now got up to 7 pages, I feel justified in having a moan about how standards are slipping here on CH. Somebody posts a question, somebody else (who shall be nameless) posts a partial solution, the OP tries it out, it doesn't work, and then a whole bunch of people just post guesses. Nobody read the command documentation; nobody tried specimen code.
Hi Salmon,
I just tried your code and it works like a charm. I cannot thank you enough for this. It's definitely going to save a lot of time for me.
Your attention to the details and understanding of the problem are great and I am sure you enjoy a healthy dose of success and satisfaction in your daily life. I wish you great success as well.
I am a photographer and I know a bit about it. Do not hesitate to get in touch with me if you need any tips about photography.
Great forums. Keep up the good work.
Lifespan of one's residue is mostly determined by what one does for common good throughout one's lifetime.
Best regards,
http://www.kankooz.com