This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 8801. |
Solve : Unfamiliar with use of the @ sign at the end of a statement? |
|
Answer» In a DOS batch FILE I am trying to understand, I have found a statement which uses the "@" sign in a way I am not familiar with. I have look in several places and my books, but I have not found an explanation. The statement is: In Perl, @ prefixes variables which CONTAIN arrays. But @8 is note known here. It's not used. "{file name}" is a directory. "[emailprotected]" is a file.Thanks for the quick replies. It was used as a file name. SEARCHING deep into the referenced program I found several folders with file names such as @1, @2, @3,.... Tom |
|
| 8802. |
Solve : How to move a full folder?? |
|
Answer» So, i have a big folder with other folders and files inside it. SyncToy 2.1 Quote Files may be in use or marked as read-only which will cause errors. The /E /C /R /I /K /Y should take care of that. As for the being in use, it would behave the same way in GUI, right?Quote from: Linux711 on April 30, 2011, 02:03:36 PM The /E /C /R /I /K /Y should take care of that. As for the being in use, it would behave the same way in GUI, right?No. It depends. But you can use Robocopy Quote While still included in Windows Vista, Xcopy has been deprecated in favor of Robocopy, a much more powerful copy tool, which is now built into the operating system.http://en.wikipedia.org/wiki/Robocopy |
|
| 8803. |
Solve : Using BATCH file: Find a number inside a file and increment it? |
|
Answer» Quote from: Allan on May 01, 2011, 02:47:25 PM It is what it is. LET's stay with the thread please. Thanks. Essentially, this thread is now complete. The OP expressed a requirement which was clarified and then addressed, despite frequent attempts at INTERFERENCE, to the OP's expressed SATISFACTION. Okay Thanks. I'll LOCK it then. |
|
| 8804. |
Solve : Add Created Date to Current Word File Name? |
|
Answer» Hi, rem Assume your %date% format is mm/dd/yyyy Why? Oooooooops, in case OP doesn't know how to get create data. Code: [Select]@echo off rem Assume your %date% format is mm/dd/yyyy for %%a in (*.doc) do ( call :CreateTime "%%a" ) goto :EOF :CreateTime setlocal enabledelayedexpansion for /f "skip=5" %%b in ('dir /tc %1') do ( set ct=%%b ren %1 "%~n1_!ct:~6,4!!ct:~0,2!!ct:~3,2!.doc" goto :eof ) endlocalhi jaynelson, Did you tried a filename with blank space? Like "HELLO world.doc" |
|
| 8805. |
Solve : python script? |
|
Answer» Hi HiThe command ./proc.py will not work from the command line. It is not part of the set or programs or commands that *DOS knows about. A script has to be run from its interpreter.This rule applies not only to Python, but all scripting languages. A Python interpreter suitable for DOS can be found at: http://www.python.org/ The CURRENT production versions are Python 2.7.1 and Python 3.2. Once you have a suitable version installed on your PC, you can INVOKE Python from the command line and pass the script as an argument. SEE the documentation for EXAMPLES. -------- *DOS, I mean the command line in Windows. Everybody calls it DOS and the documentation is found under DOS on this forum. Screen Shot of shell. |
|
| 8806. |
Solve : How to create a loop?? |
|
Answer» Hi, |
|
| 8807. |
Solve : Batch for create a copy of the original file from a shortcut file.? |
|
Answer» Batch for create a copy of the original file from a shortcut file. I have a shortcut file pointing to his original file If its not YOUR file then you are doing this over a network? With a shared path to HIS file which just happens to be a shortcut? Guessing this is a remote system on a network SINCE if you just wanted to make an exact copy of a file you could do it through windows locally. Also guessing that this is not a one time copy since you could simply double-click on the shortcut to navigate to the file and get a copy that way if it was a 1 time copy. If you right-click your shortcut you can select properties, and then view the target path. Then select that target path and use that target path in a batch file such as xcopy shortcut_target_path\file_you_want.* c:\drop_file_here\*.* /s/d/y Replace shortcut_target_path with the target path that you got from your shortcut. If there are any spaces in the path you will need to BIND it with " ". Also if you are using Windows Vista or 7, you will want to use robocopy instead of xcopy with different switches. Trying to push a shortcut.lnk into a batch is just going to be nothing but trouble. If you declare the UNC path directly, you will be better off. http://www.uwplatt.edu/oit/terms/uncpath.html If you run into a UNC path issue, you can always create a mapped drive to the folder location where that file resides such as X: Then use xcopy x:\file_you_want.* c:\drop_file_here\*.* /s/d/y or the robocopy equivilant if Vista or 7 at your end. And you have to bind the origin target path with " " if there are spaces.It's done Dave. In autohotkey. I hope the next time will be more simple. Really I am afraid. Best Regards |
|
| 8808. |
Solve : Batch command help? |
|
Answer» Hello gurus! |
|
| 8809. |
Solve : Are there any such CMD commands to reset BIOS?? |
|
Answer» Are there any such CMD COMMANDS to reset the BIOS BACK to default settings including CHANGING the USB Legacy from disabled to enabled, or do I need MS-DOS? Does the CMD even have full control over the BIOS without a PS/2 keyboard?Back to default can be usually done by jumper setting on main board or removing the cmos battery and then replacing teh cmos battery after a few minutes for the cmos to lose its settings and default to default. Some bios's also have a feature to select to set all settings back to default. |
|
| 8810. |
Solve : run 2nd and 3rd bat file 5 min after running 1st bat file? |
|
Answer» Hi C:\test>type mainbat.bat Dear SATexas Thank you very MUCH for your help. I modified your codes to the followings but it seems like it is not working. After running FBHI for 1700 second the program closed itself and did not started HFI.bat or min5ha.bat or VI.bat. Did I missed anything in the code? I don't mind if they (HFI, min5ha and VI) START one after one after 60 second in different command window. Thank you very much ***********. @echo off call del.bat echo return from delbat.bat call FBHI.bat echo return from FBHI.bat echo Use sleep command for delays rem sleep 60 sleep 25 call HFI.bat echo return to main from HFI call min5ha.bat echo return to main from min5ha.bat call VI.bat echo return to main from VI.bat echo The End echo BYE *********Still not working !! |
|
| 8811. |
Solve : Copy files to ddmmyyyy folder? |
|
Answer» Hi |
|
| 8812. |
Solve : set time in batch + 10sec more!? |
|
Answer» hi i want set current time + adding 10 second more to my batch file, like: Like Dave asked, why are you doing it that way, and not using a simple 10 second delay? Quote from: Salmon Trout on August 09, 2011, 11:56:56 PM Like Dave asked, why are you doing it that way, and not using a simple 10 second delay?because in "AT" command you must set time, you can't use delay! But you want it to happen in 10 seconds time. So why use AT? Quote from: behzad-007 on August 08, 2011, 04:32:48 AM i don't want 10 second delay! It doesn't make sense. Why do you need the scheduler and not use a time delay as suggested? Does the AT command even support seconds? The system scheduler (GUI) does not. Batch code does not really do date/time computes very well. All data is seen as a string, so even though you can do integer arithmetic, you run into that pesky problem of the seconds possibly carrying over to the next minute which in turn can carry over into the next hour and so forth. Pretty soon it's next year and then where are you? VBScript can handle the date/time arithmetic and there is a CLASS for the AT scheduler. You could always count one Mississippi, two Mississippi etc. When you get to ten Mississippi launch the missiles command. If you use military cadence, you can improve the ten second precision.Quote from: behzad-007 hi Judging by this, I am not convinced he knows the difference between seconds and minutes. Hi Sidewinder, I agree with you. Both AT and SCHTASKS don't support seconds at all. Yes, it's difficult to calculate data/time in batch code, especially we need consider the next hour/month/year and leap-year. But we can use Epoch. You may want to have a look at the fuctions of Ritchie Lawrence. http://www.commandline.co.uk/lib/treeview/index.php |
|
| 8813. |
Solve : Batch to move files by date? |
|
Answer» Hi. I need some help as I don't understand how this could be done. |
|
| 8814. |
Solve : WINRAR command line? |
|
Answer» How can i delete *.rar after i extracted files from it in cmd?"C:\Program Files\WinRAR\rar.exe" e D:\test\1.rar D:\test\archive\' How can i delete *.rar after i extracted files from it in cmd?thats how |
|
| 8815. |
Solve : Rename files? |
|
Answer» An application is creating ASCII files. |
|
| 8816. |
Solve : Winrar help? |
|
Answer» Hi, I need archive file name as like the source file name(Griddatafortheperiod20110503.txt) This should LET you specify the name for both. Is this what you need? Code: [Select]set path="C:\Program Files (x86)\WinRAR\";%path% set /p textfile=Type the name of the file: rar a -df -ep -mt2 C:\%textfile%.rar C:\%textfile%.txt pause I READ your question again, and I think I might have MISINTERPRETED your question. Do you want the batch to scan the folder for all text files and compress each one into a .rar file?Hi Linux711, Thanks for your immediate reply... i TRIED your code its working fine for me and i got the result as i needed. thanks... Shan |
|
| 8817. |
Solve : Help with bat file? |
|
Answer» This is my FIRST attempt to make a bat file. I'm using Windows XP and I've tried using cmd to get to the files but it keeps stopping at C:\Documents and Settings\MrPiggss\Desktop instead of going into the My Documents folder. This is my first attempt to make a bat file. I'm using Windows XP and I've tried using cmd to get to the files but it keeps stopping at C:\Documents and Settings\MrPiggss\Desktop instead of going into the My Documents folder.cd WebCache del /F *.* cd .. rd WebCache @Rustys the reason I'd like a bat is because I have to clear these 2 folders every time to play a game. If I don't the game crashes. Rather than manually going through my computer yada yada yada... if I had a bat I COULD just double click it would be easier. @DanCollins do I need to specify the full location i.e. C:\Documents and Settings\MrPiggss\My documents\Battlefield Play4Free\WebCache or just do it as you have shown?Quote from: MrPiggss on August 13, 2011, 10:21:30 PM DanCollins Code: [Select]@echo off cd "C:\Documents and Settings\MrPiggss\My documents\Battlefield Play4Free\WebCache" del /F *.* cd .. rd WebCache cd "c:\Documents and Settings\MrPiggss\My Documents\Battlefield Play4Free\mods\main\" del /F *.* cd .. rd main The above code must be saved to a batch file, deleterm.bat. The batch file can then be executed from the COMMAND line. (Or point to the batch file and double click.) C:\test>deleterm.bat p.s. Be careful when using *.* with delete. Make sure you have the correct files. You may NAME the batch file any name you please: myfile.bat "path" "" is necessary when there is OPEN space inside the path. |
|
| 8818. |
Solve : Check if file exists? |
|
Answer» Hi All, |
|
| 8819. |
Solve : dos/windows? |
|
Answer» please can SOMEONE TELL me the difference between dos and windowsYes, if by "someone" you mean "Google" - or my current favourite search ENGINE, Duck Duck Go: http://duckduckgo.com/?q=difference+between+DOS+WindowsPimp that novel! Pimp that novel! Just about to. |
|
| 8820. |
Solve : Batch file help? |
|
Answer» Depending on which of two physical external hard drives I connect to the same USB port on my computer that drive shows up on My Computer as either Drive F: or Drive H:. |
|
| 8821. |
Solve : Add single comma in place of any number of spaces? |
|
Answer» Looking for a way to add a (SINGLE comma) in between data like below to force non comma delimited data to become comma delimited...any suggestions on how I can do this for a text document with the raw data like below in a batch ( or vb script ) so that I dont have to run this manual notepad replace 3 step process for daily data? How can I do the same thing with my data set? First row is my column headings comma « Sent to: ry8200 on: Today at 06:03:57 PM » | Reply | Quote | Delete | Code: [Select]@echo off & setLocal EnableDELAYedeXpansion del otfile.txt > nul for /f "delims=" %%i in (infile.txt) do ( call :sub %%i ) echo. type otfile.txt goto :eof :sub echo %* :loop echo/|set /p ="%1," >> otfile.txt shift if "%1"=="" ( goto :end ) goto :loop :end echo. >> otfile.txt Output: c:\test>comma2.bat 134-2 [emailprotected] MikeSmith 927 yes no 134-2 [emailprotected] MikeSmith 927 yes no 134-2 [emailprotected] MikeSmith 927 yes no 134-2 [emailprotected] JoeLong 927 yes no no yes 134-2,[emailprotected],MikeSmith,927,yes,no, 134-2,[emailprotected],MikeSmith,927,yes,no, 134-2,[emailprotected],MikeSmith,927,yes,no, 134-2,[emailprotected],JoeLong,927,yes,no,no,yes, c:\test> ref: http://stackoverflow.com/questions/4479734/echo-with-no-new-line-cr-lf That kind of work can be done by a spreadsheet program.1. This thread has been revived by ry8200 after a gap of over two and a half years. ry8200, if you are genuine, and not Bill's sock puppet, as certain internal evidence suggests, start your own thread. Better still, read this one, where the solution was clearly described by my friend Dias de Verano, in February 2009. 2. Fred35 is, as I suspected ever since he first appeared, Billrich. Honestly Salmon Trout - Sock puppet??? Are you kidding me... If this is how a new person is treated in this forum, then I'll take my request somewhere else. I am a real person with an issue that falls in line with this post and the previous issue that DaveLembke had; so I thought it would make sense to revive this post. Anyway, moving on. The new issue I'm having is two of the fields of data, called "fn" and "display" have spaces in them (for example "Display" = "John Smith D1234567"), that I need to keep, but I want to replace all the other spaces with a comma. The data pulled from my DSQUERY is: samid upn fn ln display canchpwd pwdneverexpires disabled 123-2 [emailprotected] John Smith D1234567 John Smith D1234567 yes no no 456-2 [emailprotected] Mike Smith U1234567 Mike Smith U1234567 yes no no The output would need to look like this: samid,upn,f,ln,display,canchpwd,pwdneverexpires,disabled 123-2,[emailprotected],John Smith,D1234567,John Smith D1234567,yes,no,no 456-2,[emailprotected],Mike Smith,U1234567,Mike Smith U1234567,yes,no,no Did you read what was said about starting your own thread? You have revived a thread from 2009. Anyhow, @echo off setlocal enabledelayedexpansion set InputFileName=Input.txt set OutputFileName=output.csv set line=1 if exist "%OutputFileName%" del "%OutputFileName%" for /f "tokens=1-11 delims= " %%A in ('type "%InputFileName%"') do ( if !line! equ 1 ( set output=%%A,%%B,%%C,%%D,%%E,%%F,%%G,%%H ) else ( set output=%%A,%%B,%%C %%D,%%E,%%F %%G %%H,%%I,%%J,%%K ) echo !output! >> "%OutputFileName%" set /a line+=1 ) echo Input: echo. type "%InputFileName%" echo. echo Output: echo. type "%OutputFileName%" Input: samid upn fn ln display canchpwd pwdneverexpires disabled 123-2 [emailprotected] John Smith D1234567 John Smith D1234567 yes no no 456-2 [emailprotected] Mike Smith U1234567 Mike Smith U1234567 yes no no Output: samid,upn,fn,ln,display,canchpwd,pwdneverexpires,disabled 123-2,[emailprotected],John Smith,D1234567,John Smith D1234567,yes,no,no 456-2,[emailprotected],Mike Smith,U1234567,Mike Smith U1234567,yes,no,no |
|
| 8822. |
Solve : show batch output in msg box!? |
|
Answer» hi it is so much cleaner to just write a program in c, copy it to system32, and then call it from batch by just typing msgbox [bla bla] You can do this already from VBscript Quote from: Salmon Trout on August 07, 2011, 01:07:01 AM You can do this already from VBscript ... and you can do a lot more things... As I shall PROCEED to demonstrate... Code: [Select]' Make Shell object available Set Shell = CreateObject("Wscript.Shell") ' Force use of cscript.exe so we can use console input If Instr(1, WScript.FullName, "CScript", vbTextCompare) = 0 Then Shell.Run "cscript """ & WScript.ScriptFullName & """", 1, False WScript.Quit End If ' Get console input from user ' 1. Write prompt to console, no newline wscript.stdout.Write "Enter drive letter: " ' 2. Get user input terminated by Enter UserInput = Wscript.StdIn.ReadLine ' 3. Just get first character in case they type C: or similar DriveLetter = Mid(UserInput,1,1) ' Start building string to pass to messagebox ' Force drive letter to upper case (just because we can!) MessageString = "Drive letter is: " & UCase(DriveLetter) ' This is the string we pass to Shell for execution FsUtilString = "fsutil volume diskfree " & DriveLetter & ":" ' Start FSUtil running Set oExec = Shell.Exec(FsUtilString) ' While it has not yet finished... Do While oExec.StdOut.AtEndOfStream <> True ' Get each line in turn from fsutil FsUtilOutputLine = oExec.StdOut.ReadLine ' Split the line at the colon SplitLineArray = Split(FsUtilOutputLine,":") ' We have split Array has 2 elements, 0 and 1 ' Because there is 1 colon in each line LineText = SplitLineArray(0) ByteText = SplitLineArray(1) ' Force the bytes value string into a number ByteNumb = Eval(ByteText) ' Some HANDY values demonstrated KiloBytes = ByteNumb / 1024 MegaBytes = ByteNumb / (1024 * 1024) GigaBytes = ByteNumb / (1024 * 1024 * 1024) ' We'll show GB in brackets after the bytes figure ' We'll reduce the large number of decimal places to just 2 GBFormat = FormatNumber(Gigabytes,2) ' Build up the string for the message box ' Insert a carriage return / line feed after each line (except the last) ' So that they will appear as separate lines in the box MessageString=MessageString & VBcrlf & LineText & ":" & ByteText & " (" & GBFormat & " GB)" Loop ' Retval is a dummy value in this case since we are only using 1 Button (OK button) ' Therefore we are not concerned about the return value Retval = MsgBox(MessageString, vbOKOnly, "Disk Free and Used Space") thanks for reply this code is work, but i don't know vbScript language Quote from: behzad-007 on August 07, 2011, 07:13:05 AM thanks for reply Now is the time to start learning! I put lots of comments in there. Or you have batch code above. You can do it in 5 lines of batch Code: [Select]@echo off Set /p drive=Enter Drive Letter: fsutil volume diskfree %drive%: > text.txt <text.txt msg %username% del text.txt In fact you can do it in 1 line Code: [Select]@Set /p drive=Enter Drive Letter: & echo Drive %drive%: > text.txt & fsutil volume diskfree %drive%: >> text.txt & <text.txt msg %username% & del text.txttnx so much 5 line batch worked! but 1 line code is not WORKING in my pc!! Quote from: behzad-007 on August 08, 2011, 03:17:48 AM but 1 line code is not working in my pc!!Yes it has an error I will try to fix it |
|
| 8823. |
Solve : Buffer = ? In MS DOS config.sys what is the maximum? |
|
Answer» I had a PC die on me that was running a Operating System used in CNC programming. I changed the PC and had Win 98 installed which is what was on the other. When trying to transfer files within this DOS DRIVEN software I get a Buffer size exceeded error. In Config.sys, what is the maximum number I could put in this field? Or is it hard coded. Also, is this just a string buffer? I had a PC die on me that was running a Operating System used in CNC programming. I changed the PC and had Win 98 installed which is what was on the other. When trying to transfer files within this DOS driven software I get a Buffer size exceeded error. In Config.sys, what is the maximum number I could put in this field? Or is it hard coded. Also, is this just a string buffer?0 to 255 the more you add,more memory is used,i have 768mb of memory on one of my computers and i have added 180 buffers and it is faster. Just edit the config.sys file example buffers=180 then save and exit you must restart your computer for this to take effect. and I am running xp pro sp2 This thread is a year old (not that the answer would make any more sense if it wasn't).180 buffers ? ? ?Nothing in config.sys changes the way Windows XP works. In fact, No version of NT even Looks at config.sys during startup. Any perceived speed increase is only perceived and not actual.Don't spoil his fun....he may spend weeks working on another non-functional speed tweak...Quote from: patio on May 05, 2011, 07:04:59 AM Don't spoil his fun....he may spend weeks working on another non-functional speed tweak...Some all around speed "tips": -If you wear unmatched socks it can increase file access times by over 50%! -People with fillings should avoid using the mouse, and use keyboard operations where possible. Experiments done on guinea pigs have revealed that this can increase throughput by a factor of 5 compared to a guinea pig sitting on your keyboard. -If you have a game controller plugged it, put flame stickers on it. It makes everything go faster. -If you have more then 512MB of memory, this can slow down newer operating systems like Windows Vista, because they deal with memory in something called Blubbors*. a Blubbor takes a long time to transfer, and the more blubbors you have, the longer everything takes. Windows Vista has a minimum requirement of at least 3.51 Blubbors, but has been known to run on machines as low as a half blubbor (also known as a scaligree**). Anyway, the more blubbors the slower t hings go, and the more memory you have, the more blubbors, so if you remove memory things will go faster. No arguing with logic. *Blubbors do not exist. If you think you are seeing a blubbor, it's a hallucination. Seek medical aid immediately. **scaligree's were discovered in 1636 by the Algonquin native tribe in North America. It smells like daffodils.Blubbors do exist... |
|
| 8824. |
Solve : Batch file to login to my mail id? |
|
Answer» Hi All, Is this possible in DOS? Is it possible for us to send inputs to webpage through command line. Not that I'm aware of. You might TRY VBScript which has several WAYS of handling this. One would be to fire up the browser and send keystrokes to the rendered page. This can be successful, but timing is everything and any misfire can produce unexpected results. A second way would be to create an instance of the browser where you can script both the browser and the rendered page. You can use this little snippet as a template which shows off the second method: Code: [Select]Set IE = CreateObject("InternetExplorer.Application") Set WshShell = WScript.CreateObject("WScript.Shell") IE.Navigate "http://www.yahoomail.com" IE.Visible = True Do WScript.Sleep 5000 Loop While IE.Busy IE.Document.All.Item("login").Value = "username" 'Change username as needed IE.Document.All.Item("passwd").Value = "password" 'Change password as needed WshShell.SendKeys "{ENTER}" Good luck. @Balwinder Singh: START your own thread and please be more specific. This is probably nothing but I'm tired of chasing shadows around every corner. |
|
| 8825. |
Solve : Abusing the old DOS DEBUG.COM program? |
|
Answer» Some OLDER articles about DOS and batch programming MENTION the program named DEBUG.COM to write short bits of code to change things. |
|
| 8826. |
Solve : Append file extensions to a number of files? |
|
Answer» Hey all! 01 Audioslave - Revelations.mp3 Now, if you for some reason want to change the suffix from "mp3" to something like, I don't know, maybe aac. You would type something like this in the Windows command line. Code: [Select]ren *.mp3 *.aac You hit Enter and you're done. They should now be listed as... Quote 01 Audioslave - Revelations.aac It's easy when they all have something in common, like the "mp3" suffix in this case. But what if they don't have anything in the name that's common to all files? You won't be able to use any combination of wildcard characters to match the files you want. Am I right? Example 2 It's easy when they have something in common. Like this... Quote 01 Blur - Bang In this case you have "blur" as the common denominator. So you could type something like this... Code: [Select]ren *blur* *.mp3 That should add the "mp3" suffix to all files containing the word "blur". So you get... Quote 01 Blur - Bang.mp3 But what if you don't have a common denominator in all files, like in example 2? I tried typing this... Code: [Select]ren 01*;02*;03*;04*;05* *.mp3 But the command line only returned syntax error. So I tried replacing the semicolon with a plus sign, like this... Code: [Select]ren 01*+02*+03*+04*+05* *.mp3 Command line just says that the file could not be found. Inserting spaces before and after the plus sign doesn't help either. It just gives syntax error. So there doesn't seem to be a way to cheat on this. While you may be able to select multiple files using the "file+file" format, you can't use the ASTERISK character at the same time in that same command line. So I tried... Code: [Select]ren 01* *.mp3 This works, but you have to repeat it for every file. So it would be like... Code: [Select]ren 01* *.mp3 ren 02* *.mp3 ren 03* *.mp3 ren 04* *.mp3 ren 05* *.mp3 So, now I'm thinking that one may need to create a batch file. But wait a second... a batch file?... just to perform this simple task? Is that really necessary? Is there no other way around? You would still need to write the batch file. That consumes time, and while at it you may as well go ahead and add "mp3" to the files manually, one by one, in the Windows Explorer! So... Thoughts? Ideas? Let me know!Quote from: Fractalogic on August 07, 2011, 11:14:59 AM I have a bunch of mp3 files with missing file extensions. What is the best way to append the "mp3" suffix to them? You appear to like typing, judging by the length of your post, so maybe you would prefer to rename them all manually using Explorer, but if you are prone to the type of accident that strips files of their extensions, then the time spent writing a batch file, or a command-line one-liner that you can save as a text file and paste to the prompt, will soon be saved. In any case, you will only need to copy and paste the code below, making any alterations needed to fit your particular needs. Code: [Select]@for /f "delims=" %A in ( ' dir /s /b /a-d "C:\My MP3 Collection\Folder in Question" ' ) do ren "%~dpnxA" "%~nA.mp3" Note: 1. This is for the prompt. 2. If you want to use it as a batch file change the single percent signs % to double ones %% so that %A becomes %%A and %~dpnxA becomes %%~dpnxA and %~nA becomes %%~nA. 3. It operates on all files in the named folder and all files in any sub folders also. If you don't want subfolders to be affected, delete the /s switch from the DIR command in the brackets. 4. It will add the .mp3 extension to all files that do not have an extension, and it will replace any other extension with .mp3. Quote from: Salmon Trout on August 07, 2011, 12:01:33 PM You appear to like typing, judging by the length of your post, so maybe you would prefer to rename them all manually using Explorer, but if you are prone to the type of accident that strips files of their extensions, then the time spent writing a batch file, or a command-line one-liner that you can save as a text file and paste to the prompt, will soon be saved. In any case, you will only need to copy and paste the code below, making any alterations needed to fit your particular needs. I sure do! That's why I'm still stuck in DOS! Duh! I would say that my primary objective is to learn how to do things like these. I am very eager to learn as much as possible about computers in general. I have one question. What book do I need to read to UNDERSTAND the command line you just wrote? No, seriously, what type of books cover these kind of things? Is that even a command? Or is it a script?... How do you paste a line like that into CMD? As far as I know it's not possible. Enlighten me!Quote from: Fractalogic on August 07, 2011, 12:54:08 PM How do you paste a line like that into CMD? As far as I know it's not possible. Enlighten me! Get whatever you want to paste into the clipboard and then in a CMD window: Left click the icon in the top left corner then select "Edit" from the menu that appears, then finally select "paste" --- or alternatively --- If you do not have QuickEdit enabled, you can right click in the window and select "Paste" from the menu that appears. If you have QuickEdit enabled, just right click and the text will paste itself. Select QuickEdit mode from the top left hand corner icon menu - Properties - Options - Edit Options. Quote from: Salmon Trout on August 07, 2011, 01:10:50 PM Get whatever you want to paste into the clipboard and then in a CMD window: Wow! Pasting in CMD really works! How about that! Thanks! QuickEdit needs to be enabled in order to MARK and copy from CMD, right? I just tried that command line and it worked just as expected. There are no duplicates of the "mp3" suffix, so everything is okay. Except for two PICTURE files, you know the album art kind of thing. But they are still there so I can change them back manually, it's no big deal. You did warn me that this will change the extension for all files in the folder and all sub-folders to "mp3". It was my mistake. I didn't have any sub-folders by the way, so that's just fine. Now I would really like to know where I can learn more about this?...Quote from: Fractalogic on August 07, 2011, 01:27:40 PM QuickEdit needs to be enabled in order to mark and copy from CMD, right? No, it doesn't have to be enabled, it just makes it slightly quicker. To copy from a CMD window In each case I am referring to the menu you get when you left click the top left corner icon in the CMD window: Without QuickEdit enabled: Select Edit, then select Mark, then using the left mouse button, highlight (mark) the text you want to copy, then EITHER select Edit, then select Copy OR just press ENTER QuickEdit enabled: Using the left mouse button, highlight (mark) the text you want to copy, then EITHER select Edit, then select Copy OR just press ENTER As you can see, QuickEdit cuts out having to go to the window menu first. Whichever way you do this, the highlighted text reverts to unhighlighted appearance when it gets copied to the clipboard. It can then be pasted in the normal way into other windows, programs, etc. Quote Now I would really like to know where I can learn more about this?... It is hard to know where to suggest - the web is full of batch tutorial websites. I did have a book years ago called "MS-DOS Command Reference" by Microsoft Press but the modern Windows batch language has evolved beyond that - This is quite a good introductory tutorial, by Ashley J Mills at the University Of Birmingham (England), it's all over the Web in various places https://supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/tutorials/win32scripting/win32scripting.html Or Google for Windows CMD Tutorial, batch examples, etc. Be inventive. Take the initiative - when you are developing a script, instead of hitting a forum and asking "How do I add two numbers together?", it is quicker to search Google for "Win32 batch arithmetic" and study the hits you get. My advice is don't get too tied down with batch - if you find you have a knack for it, (or if you don't!) take a look at Visual Basic Script, (VBscript) and Windows Powershell especially. Quote from: Salmon Trout on August 07, 2011, 02:01:38 PM Take the initiative - when you are developing a script, instead of hitting a forum and asking "How do I add two numbers together?", it is quicker to search Google for "Win32 batch arithmetic" and study the hits you get. I didn't mean to say that you are not perfectly welcome to ASK any questions you like on here and I and others will be very happy to help! |
|
| 8827. |
Solve : convert text 2 binary with batch file!? |
|
Answer» hi |
|
| 8828. |
Solve : Write DIR listing appending to file from multiple depth sub directories? |
|
Answer» I am trying to find a way to write to file a list of all directories, sub-directories, and file names that are in those directories and sub directories without having to exclusively direct the DIR command to each physical directory of over 628 sub directories in that main directory. I am guessing there may be a way to make a FOR loop in a batch file when executed from a starting directory write to say a directory outside of that directory the appending file and folder contents without a CRC Error caused by trying to write back to location being used for DIR possibly sort of like the XCOPY CRC issue and using something similar to DIR>>Listing.txt to pass it appending to the Listing.txt file. But I am stumped on how to pass this DIR command to retrieve information for sub folders and its file contents as a wild card I guess you could call it to search and report back all without having to give it exact paths to follow deeper in and for all directories and subdirectories. Anyone have any code suggestions to make this happen? |
|
| 8829. |
Solve : Retrieve last field in each line? |
|
Answer» I WANT to read a LINE from a text file, and am interested in assigning the last field to a variable. How do I do this without hardcoding the position, I want the script to be flexible ENOUGH to handle varying number of columns.Is the 'text' file space delimited?We have been asked to supply script code to extract the last "field" from a line of text, but we have not been told how the fields are delimited. Dusty has already asked about this. Until this is known, it will be difficult to PROVIDE a suitably robust SOLUTION. |
|
| 8830. |
Solve : Output to a file? |
|
Answer» I am trying to output information from a batch file to a text file. I am using a batch file program which searches a single text file, line by line for certain names and if they exist, it outputs the name to the screen. I wish to also out put the name to ANOTHER text file. The program goes something like this: |
|
| 8831. |
Solve : Registry Editing? |
|
Answer» Hey, I want to MAKE a batch file that changes the value of the wallpaper in Windows 7. I know it is located at: HKEY_CURRENT_USER\Control Panel\Desktop\Wallpaper |
|
| 8832. |
Solve : how to create pdf file in dos mode? |
|
Answer» How to create pdf file in dos mode, and how to print dos file on usb printer |
|
| 8833. |
Solve : DOS command help? |
|
Answer» Hello, This could probably be done in AutoIt or VBScript, but I can't help you because there is no such item "Email History" on the tools menu. I think he probably means Mozilla Thunderbird, but he hasn't been back, so we may never know. This question seems a bit hackish/script kiddieish - I mean, why not just do it in the GUI? I note he wants to use a "drive F" which could be a pen drive... It might not be his computer he wants to do the exporting on. |
|
| 8834. |
Solve : Opening two files at once via a .BAT file? |
|
Answer» I have written a fairly extensive batch file program that automates processing of meteorological data for my work. The program works WELL, but in my last step, I would like to be able to OPEN two external programs/files at once. One is an executable file (WRPLOT.exe) and the other is an excel SPREADSHEET. The way I have it right now, the WRPLOT opens and the spreadsheet won't open until WRPLOT is closed/terminated. |
|
| 8835. |
Solve : keep batch file on top of other windows? |
|
Answer» Hey all, STARTExample" start "Peek-A-Boo" /MIN "new-batch.bat " Would tell CMD stat new-batch with a window in the task bar that says "Peek-A-Boo" but not on the screen. That is the best I can do. For more info, see the link above. Quote from: Geek-9pm on May 18, 2011, 10:07:17 AM That is the best I can do. And very good it was too. Quote from: Geek-9pm on May 18, 2011, 10:07:17 AM Off the top of my head I don't know how you tell windows to keep on DOS box on top. You can't easily with anything built-in but there is a downloadable program called CMDOW which can do this among other things (move, resize, send to back, bring to front, keep on top, tile horizontally or vertically, [and untile again] cascade, [and uncascade], activate, deactivate, minimize, maximize, restore. and more!) Beware though because some antivirus programs (stupidly IMHO) flag it as suspicious apparently because it can be used to completely hide a window. SALMON: Would like to keep it native to most OS's but it seems like an awesome program Geek: If i open all programs as /min it works although winword and powerpnt 2010 is an exception as it minimizes the first instance and the rest open non minimized. This should be good enough though thanks for all your help! |
|
| 8836. |
Solve : help with taskkill? |
|
Answer» Hello, I have a problem if you can call it that way, I want to make a batch file that only allows some executables to run. For example I want to allow only skype.exe and YahooMessenger.exe or any executables written in a file, and the rest of executables to be taskkilled (taskkill *.*) in a loop. Is it POSSIBLE? Can someone help me with this please? |
|
| 8837. |
Solve : Find newest folder? |
|
Answer» Hello - I am trying to write a batch file to find the newest folder under a CERTAIN directory. I then want to cd to that dir and get a list of files. I'm having trouble with the first part....finding the newest folder. Does anybody have any tips? If you filter out the directories and sort them descending, the newest one will be the first in the list. Using /O-D, the newest one will be the last in the list. It's /OD which sorts dates from earlier to later. /O-D sorts later to earlier. Using this, you can iterate through all the directories with FOR, assigning each name in turn to a variable. After the loop (which can be a one liner) the variable will hold the name of the last in the list, which will be the newest by date. Thus the Goto is avoided. Does the OP wish to filter out junction POINTS? Something like the below would just get the subfolders under a folder Code: [Select]@echo off for /f "tokens=1-4* delims= " %%A in ( ' dir /tc /ad /od ^| find "<DIR>" ^| find /v "<JUNCTION>" ' ) do if not "%%E"==".." if not "%%E"=="." set NewestFolder=%%E Echo Newest folder is "%NewestFolder%" Quote from: Salmon Trout on May 21, 2011, 01:41:51 AM Using /O-D, the newest one will be the last in the list. It's /OD which sorts dates from earlier to later. /O-D sorts later to earlier. Using this, you can iterate through all the directories with FOR, assigning each name in turn to a variable. After the loop (which can be a one liner) the variable will hold the name of the last in the list, which will be the newest by date. Thus the Goto is avoided. Must be me. But /o-d sorts descending by date with the newest folder first while /od sorts ascending by date with the newest folder at the bottom of the list. In any case, seems like a lot of code to eliminate a goto. NT batch code has a limited instruction set, might as well use them. I see I was preempted by another post. This might be the answer to all of CH problemsQuote from: Sidewinder on May 21, 2011, 05:44:06 AM In any case, seems like a lot of code to eliminate a goto. It's not just "eliminating a goto". This would do that Code: [Select]for /f "delims=" %%A in ('dir /b /ad /od') do set lastfolder=%%A dir %%A My code was also eliminating junction points which may or may not be required (The OP has not replied to my question - not surprising as it's very likely Billrich) and also the . and .. entries that the full DIR listing includes. Quote from: Sidewinder on May 21, 2011, 05:44:06 AM In any case, seems like a lot of code to eliminate a goto. NT batch code has a limited instruction set, might as well use them. In any case, you only needed the goto because you got the sort order around the wrong way. Quote from: Salmon Trout on May 21, 2011, 06:52:25 AM In any case, you only needed the goto because you got the sort order around the wrong way. I gotta stop falling into the rabbit hole. The sort order was purposely chosen to save the time of iterating the entire directory contents. Also curious why eliminate the junction points? Could be wrong, but don't they act as links to a directory, making the directory accessible by using an alias? Seven hours till End Of Days (local time) when all this becomes meaningless. But just in case, I'll post this for prosperity or until the next End of Days is scheduled. Quote from: Sidewinder on May 21, 2011, 08:45:25 AM The sort order was purposely chosen to save the time of iterating the entire directory contents. OK, I'll concede that, but it's hardly going to be a big saving. Maybe on a P133 with 64 MB of RAM (min spec for Win2k) I guess. Quote Also curious why eliminate the junction points? Could be wrong, but don't they act as links to a directory, making the directory accessible by using an alias? I showed elimination of junction points from the directory listing in case it was required; if not it is a simple matter to alter the code. Quote from: Sidewinder on May 21, 2011, 08:45:25 AM Seven hours till End Of Days I need some new eyeglasses, I think, because I THOUGHT that 6 pm was going to be the "Rupture", and I had gathered together materials for hernia treatment for my whole family. Quote from: Salmon Trout on May 21, 2011, 09:07:23 AM I need some new eyeglasses, I think, because I thought that 6 pm was going to be the "Rupture", and I had gathered together materials for hernia treatment for my whole family. Could you do a favour for those of us in a later time zone, and post a warning to us when it starts for you? I still have to get my disguise ready.I'm having my Guinness and Single Malt Scotches in vast amounts just in case... I started a Tab since noone will be here tomorrow.ROL at what BC said to warn the later time zones that the end is happening in their zone...lol |
|
| 8838. |
Solve : clipping digit from write appending to logfile? |
|
Answer» This is probably easy to explain, but my google search hasn't given me a reason why digits are clipped when executing for example below and the 1 is not WRITTEN to file unless there is a space between the 1 and the >> write appending to log file. This is probably easy to explain, but my google search hasn't given me a reason why digits are clipped when executing for example below and the 1 is not written to file unless there is a space between the 1 and the >> write appending to log file. It's because of numbered console streams. lol....Geek-9pm Thanks Salmon for pointing out the correct terminology of Numbered Console Streams! Now I understand what it is instead of just saying..."well you have to add a space...why I dont really know ....other than if I dont, it clips digits... so just add the space." I wasnt satisfied with just knowing that adding a space makes it work correctly ( without knowing exactly why ) vs without a space clipped the digit, while it wouldnt bother text that is bound tight to it. I am the type of person who likes to understand "why" something behaves the way that it does ......Instead of being satisfied with "well it does it and who cares as to why and how, ...it works so just use it! " Given the correct terminology I was able to then find more info that helps me understand this: Stream Redirection: The explanations regarding the less and greater than symbols aren't complete without knowing what goes where and how to manipulate them. Handles: 0 - Standard input(normally keyboard but can be redirected from file) 1 - Standard output(Normally console but can be redirected) 2 - Standard error(Normally console but can be redirected) 3 - 9 - Undefined but semi usable, basically useless - at least in BATCH scripts. Above we were implicitly redirecting, the less than SYMBOL implies that file contents will be sent to the standard input and the greater than symbols implies that the standard output will be sent to file. To explicitly redirect the number of the handle must come IMMEDIATELY before the redirection symbol, no spaces allowed. This is essentially the same script as above: echo on 1> example.txt echo echo hello 1>> example.txt echo exit cmd 0< example.txt del example.txt pause As found at: http://judago.webs.com/batchoperators.htm |
|
| 8839. |
Solve : Very Confused By MSDOS (Making Batch Program)? |
|
Answer» Okay so I'm heavily a Linux user but I'm on Windows right now. I need to build a simple batch program to connect to a webpage a set number of TIMES and save the result in a unique text file each time. If you're more curious, the reason I am trying to do this is for testing of a certain error that only occurs some of the time. I want to figure out how often it occurs, and if there's any pattern to the occurrence (as I hope that may help with fixing it). set UNIQUE=%UNIQUE%1 What happens is it just downloads and nothing is renamed. The file sits with this horribly long name that WGET GIVES it by default. I had it renaming earlier (can't remember what I changed) however I can't figure out how to increment in MSDOS. It just APPENDS 1s onto the end like this: result1.txt result11.txt result111.txt ... I want: result1.txt result2.txt result3.txt ... And yes I've been searching Google endlessly and not having much luck. I hope someone here can help me who is more familiar with Batch.Is this the aversion you have? http://www.gnu.org/software/wget/manual/wget.html FYI thee are a number of GNU things that have been compiled for Windows. Python is one of many. http://www.python.org/getit/ I would like to help, - but long files names give me vertigo. |
|
| 8840. |
Solve : Net use weird behavior? |
|
Answer» Hello All - In a batch file I am running the net USE command to map a shared folder. I then cd to that drive and cd to the newest folder, then delete the mapped drive. When I rerun this again, the first net use statement to map the drive takes me to the last folder that I cd'd to. Why does net use behave this way? Example, my share is z: \\servername.domain.com\share\8.2\8.2.0.0.1 - the first execution takes me to the \\servername.domain.com\share\8.2\8.2.0.0.1\8.2.0.0.1.32 as expected, but the next execution takes me to the \\servername.domain.com\share\8.2\8.2.0.0.1\8.2.0.0.1.32\bin folder. So I'm not understanding why I've mapped it to a certain directory but then it seems to take it to the next level and automatically put me in the last dir I was at. That's not the behavior I am looking for.... |
|
| 8841. |
Solve : Batch File for Find and replace multipal string in any file format? |
|
Answer» I want to create a batch file for finding and replacing a string in *.vb file.Why? Do you use VB? |
|
| 8842. |
Solve : Testing for & Enumerating %~* and %*? |
|
Answer» HI All Finally joined the community after spending incalculable amounts of time combing through the site & forums. Thanks to all for lending your expertise. Although I create little 'batch' scripts regularly for deployments and various other TASKS, I often 'script' for fun. Today's one of those days. I'm writing a small .cmd file for my teammates to help them understand the various variables available at run time. Instead of writing out Code: [Select]echo %%~0 = %~0 echo %%~1 = %~1 echo %%~2 = %~2 ... echo %%~9 = %~9 rem testing arguments echo %%0 = %0 echo %%1 = %1 echo %%2 = %2 ... echo %%9 = %9 I was hoping I could leverage FOR /L instead to do something like: Code: [Select]for /L %%a in (0,1,9) do ( if defined %~%%a echo %%~%%a = %~%%a if defined %%a echo %%%a ) I don't know if I can, and how to, test whether or not %1 or %~1 have been defined via for loop. Its silly, I know. Any ideas?Tricky, but I think Ive done it Code: [Select]@echo off echo %%* = %* for /L %%a in (0,1,9) do call :test %%a %%%%a goto :EOF :test set p= call set p=%%2 if "%p%"=="" goto :EOF echo %%%1 = %2 Anyone have any improvements ??NICE - very interesting results. This seems to work well for testing arguments but not when enumerating %~* during run time. For instance... I execute the following: Code: [Select]"C:\test\script.bat" "C:\test\script.bat" two three four five six seven eight nine Which returns: Code: [Select]%* = "C:\test\script.bat" two three four five six seven eight nine %0 = "C:\test\script.bat" %1 = "C:\test\script.bat" %2 = two %3 = three %4 = four %5 = five %6 = six %7 = seven %8 = eight %9 = nine This works great for checking arguments and the like. However in situations where you might want to strip the quotes around the argument, you would have to use %~1, %~2 etc. Unfortunately there doesn't seem to be a way to do that. Dropping %~ in front of %2 fails altogether, and adding an extra % in front of that results in a literal output: %~two %~three etc. The batch works as is but was just hoping to add some logic for argument checking. I was hoping I could do something like this but I can't get it to work properly even after Code: [Select]:EVALARGS if "%~0"=="" goto :NEXT echo %0 shift goto :EVALARGS According to http://www.robvanderwoude.com/if.php I should be able to use the above example or even [%~0]==[] and "%~0"=="/?" but I had trouble there.Quote from: Phylum on May 25, 2011, 11:43:34 AM if "%~0"=="" goto :NEXT But %0 is a special argument. and is unaffected by SHIFT, which dumps %1 and replaces it with %2 and so on until all non-null parameters are exhausted. * You do know about ~d, ~p, ~n, ~x and the others? However... Code: [Select]@echo off setlocal enabledelayedexpansion for /L %%a in (0,1,9) do ( call set param=%%%%a if not "!param!"=="" ( call echo %%%%%%a is %%%%a and %%%%~%%a is %%~%%a ) ) Called with 5 parameters Code: [Select]C:\Test>nparams005.bat cat dog horse cheese "cake" %0 is nparams005.bat and %~0 is nparams005.bat %1 is cat and %~1 is cat %2 is dog and %~2 is dog %3 is horse and %~3 is horse %4 is cheese and %~4 is cheese %5 is "cake" and %~5 is cake Hi Salmon Trout I must have been out of my MIND when I put %~0. As foolish as it looks now, I meant %~1 through 9. Thank you for that! Your solution works perfectly! I struggled with trying to do what you did in the if statement, very creative! In case anyone is ever curious about argument counting without using shift Code: [Select]set argcount=0 for %%a in (%*) do Set /A argcount+=1 |
|
| 8843. |
Solve : Variable in FOR loop? |
|
Answer» Greetings. I am wanting to create a text file listing all the files in a DIRECTORY. A quick search on google provided myriad examples. The below for loop works fine. Note, I added the time stamp string in order to write the time stamp at the top of my file in my required format. FOR /r "C:\Documents and Settings\Administrator\My Documents\My Pictures" %%X IN (*.jpg) DO ( Try to debug your test batch with more ECHO statements. For example, use a simple ECHO of the variable befog and after you change it. Surprise! Delayed expansion ? A very "interesting" post from Geek. gsnidow, due to the way the Windows NT family command interpreter (which is not "DOS", by the way) processes variable expansion in FOR structures, to set and expand variables within a loop, you need to use "delayed expansion". You set it up in a batch file by including this line somewhere before the loop setlocal enabledelayedexpansion The case doesn't matter - upper or lower or a mixture of the two, all are OK. Mostly it's OK to put it right at the start after the @echo off line that starts most scripts. If you leave it out then you can't use delayed expansion variables of the !var! type Now, we come to how you use this feature within a loop, (in fact within any structure where multiple lines are enclosed in brackets) You assign (set) the variable in the normal way, by using the set command followed immediately by an equals sign and then the variable value: SET var=%%X Note that there are no exclamation marks ("exclamation points") in the above line. To read (expand) the variable within the loop you treat it like a normal variable, but with the difference that you use exclamation marks (!) and not percent signs (%): echo !var! >> c:\FileList.txt You can do all the usual variable processing stuff with such a variable. Note also that once the loop has finished (after the closing bracket of the loop) you can still access the variable but you use percent signs as normal. In the script you showed above, after the loop has finished, %var% will contain the last value that !var! held. This might be useful sometimes if you want to know the last item in a list or sequence. A point - using double colons :: as comment markers is unofficial, undocumented and unsupported, and will in certain situations (within a loop for example) break a script. Use REM or Rem or rem or ReM instead. Another point - writing ALL the commands in UPPER CASE is not compulsory. Thank you so much Geek and Salmon for the very helpful points. I have made it easier on myself by creating c:\test, and putting only 3 files in it, Test1.txt..Test3.txt. At Geek's suggestion, I have been working on only the problem part, which, with my new test folder, boils down to... FOR /r "C:\test" %X IN (*.txt) DO SET var = %X Note I am not trying to do this in a batch file now, because I want to see what is happening in the cmd window. As expected, the output of this line is... C:\...>SET var = C:\test\Test1.txt C:\...>SET var = C:\test\Test2.txt C:\...>SET var = C:\test\Test3.txt This RESULT seems to me to imply that for each iteration of the loop, it is correctly assigning the value of the current file name to the var variable. I then tried this... FOR /r "C:\test" %X IN (*.txt) DO SET var = %X ECHO %var My thought was that since, based on my assumption above, the variable is being correctly set, the next step would be to ECHO it. However, this is not the case, as the output is now... C:\...>SET var = C:\test\Test1.txt ECHO %var C:\...>SET var = C:\test\Test2.txt ECHO %var C:\...>SET var = C:\test\Test3.txt ECHO %var It seems that it is only appending "ECHO %var" to the variable value, along with the file name of the current iteration. I am thinking it must be possible to carry out multiple actions in the DO part of the loop, but I can't seem to get it. One question to the delayed execution: I am having trouble understanding why it is necessary if, based on my first results, it seems to be correctly assigning the variable value without it. @Salmon - I'm going to continue to mess with it before I simply copy and paste your line of code, so I will probably have some more questions later. As for the all caps, I'm a SQL guy, and my practice is to always put key words in all caps, because it makes the code easier to read. Once again, I very much appreciate both of your helping me as I muddle through being a newbie at this. Thank you so much. Greg Quote FOR /r "C:\test" %X IN (*.txt) DO SET var = %X ECHO %var 1. You can't do this. 2. Variables have a percent sign before and after so %var won't work. 3. Quote As expected, the output of this line is... It was just echoing "set var = " (which is wrong; lose those spaces) and expanding %X. The variable %var% was not being set correctly. Trust me. Quote It was just echoing "set var = " (which is wrong; lose those spaces) and expanding %X. The variable %var% was not being set correctly. Trust me. Ah ha, those darned spaces. All seems to be good now, so I very much appreciate the help. One last question, how do I know when to use '%' and when to use '!' to wrap my variables? Thanks again. GregQuote from: gsnidow on May 23, 2011, 05:51:16 AM how do I know when to use '%' and when to use '!' to wrap my variables? Thanks again. You use % all the time except when you want to expand a variable, in a loop or other parenthetical structure (e.g. a long form IF), which you have previously set in that structure. @Salmon - I apologize if this is a newbie question, but I don't know what you mean by expanding a variable. I read some stuff on google, but most of it was dealing with posters having issues with expanding their variables in various languages. Could you possibly put it in laymen terms? Thanks. GregWhole waiting or Salmon Trout, here is some more reading. http://www.robvanderwoude.com/variableexpansion.phpQuote from: gsnidow on May 23, 2011, 08:14:40 PM I don't know what you mean by expanding a variable. Could you possibly put it in laymen terms? OK here GOES... You create a variable with the SET command, and when you use it in a statement, it gets "expanded" by the command interpreter cmd.exe. set animal=cat The command interpreter reserves some memory space for a variable called "animal" and stores the THREE characters 'cat' in that space. later you have echo %animal% When the command interpreter processes this line it identifies the variable because of the percent signs and looks up the value of "animal" in its list of variables. It finds 'cat' so it replaces %animal% with cat and executes echo cat This process of replacing a variable's name with the value it holds is called "expansion". Thanks for the help and explanation guys. That is a great article, and it does not seem so strange now. I very much appreciate you taking time out of your busy days to consider and respond to my questions. Greg |
|
| 8844. |
Solve : read next line of source file? |
|
Answer» I need help to create a set of subdirectories two levels down in a root directory. I have to use a source file to read from but do not know how to get the next line of the source file. |
|
| 8845. |
Solve : Need MS-DOS Latest version Download info? |
|
Answer» HI, where can i find the source (MS-DOS FILE) to UPGRADE the EXISTING one? Thanks, SravanMS-DOS is a copyrighted PRODUCT. You have to buy it. Quote Microsoft MS-DOS 6 Upgrade Operating SystemUpgrade to version 6.22 from any earlier version 6.xx free from Microsoft http://www.microsoft.com/downloads/en/details.aspx?FamilyID=96cc3197-b7e5-4b31-badb-ddaac771295f |
|
| 8846. |
Solve : Old Computer with bad hard drive - need help with autoexec.bat? |
|
Answer» I have an old laptop with a bad hard drive. The laptop is an CTX Ezbook 700. The autoexec tells me I have successfully It SOUNDS like you are booting from a floppy? In which case A: and B: are reserved for floppy drives, then C will be the system (MS-DOS) drive if present, and if not that letter will get assigned to the CD-ROM. The autoexec massage must be from MSCDEX. Massage..... Post the config.sys and autoexec.bat files for review... |
|
| 8847. |
Solve : Taking the spaces out of file names in a batch of files? |
|
Answer» Hi folks, |
|
| 8848. |
Solve : Display only total files and bytes line on dir command? |
|
Answer» I am creating a batch file to backup certain directories. After the copy command, I want to compare the total files and bytes of the original directory to the backup directory to confirm everything worked ok. I have used the dir /s command, but that displays pages of files and folders, making the comparison on one screen impossible. What I want to do is display only the next to last line that shows the total files and bytes. If there were something unique in the "string" for that line, I would be fine There is something unique - its position in the output listing, so we can use a FOR loop to successively assign the line CONTAINING "File(s)" to a variable and when the loop is over the variable holds the final value. Just like dir /s, the code below will appear to do nothing for a while if the tree is a deep one with many files. Code: [Select]@echo off for /f "delims=" %%A in ( ' dir /s "D:\Folder" ^| find "File(s)" ' ) do set total=%%A Echo Total for tree is %total% Developed a bit... Code: [Select]@echo off set folder1="D:\test" set folder2="T:\test" for /f "delims=" %%A in ( ' dir /s %folder1% ^| find "File(s)" ' ) do set total1=%%A for /f "delims=" %%A in ( ' dir /s %folder2% ^| find "File(s)" ' ) do set total2=%%A for /F "tokens=1-4" %%A in ("%total1%") do ( set files1=%%A set bytes1=%%C ) for /F "tokens=1-4" %%A in ("%total2%") do ( set files2=%%A set bytes2=%%C ) Echo Folder: %folder1% Files: %files1% Bytes: %bytes1% Echo Folder: %folder2% Files: %files2% Bytes: %bytes2% if "%files1%"=="%files2%" ( echo Number of files: identical ) else ( echo Number of files: NOT identical ) if "%bytes1%"=="%bytes2%" ( echo SIZE of data: identical ) else ( echo Size of data: NOT identical ) Code: [Select]Folder: "D:\test" Files: 2043 Bytes: 165,993,132 Folder: "T:\test" Files: 2043 Bytes: 165,993,132 Number of files: identical Size of data: identical |
|
| 8849. |
Solve : Detect and Eject Removable Disk in cmd? |
|
Answer» hi Wlll not eject automatically. USB stick is safe to remove manually at any time. That advice is reckless. Delayed write and programs that have a file open on the device will not take too kindly to your yanking the device from the port. Could not find a script to do a safe remove but you can enter this command in a batch file which will present the GUI: Code: [Select]RunDll32.exe shell32.dll,Control_RunDLL hotplug.dll There are also third PARTY programs which claim to ACCOMPLISH this. Google will be helpful here. Good luck. BTW: Didn't Rock Hudson die some years ago. Good to see the cemetery crowd on CH.Quote Wlll not eject automatically. USB stick is safe to remove manually at any time. Agreed ...shifty advice at best.Quote from: behad-007 on July 27, 2011, 02:44:33 AM Tnx for reply, Transfusion wrote: "Something like this? http://www.911cd.net/forums//index.php?s=924b5513860a93a2c9bef812b0718a05&showtopic=13917&pid=132133&st=0&#entry132133" The Transfusion method Is for a CD drive with a door. The OP,behad-007, is concerned with a USB storage device. _______________________________________ ______ There is safely remove USB icon at the lower right. Remove USB drive when Safely Remove Hardware icon APPEARS at the lower right.Quote from: Fred35 on July 28, 2011, 05:46:31 PM Transfusion wrote: _______________________________________ _____ When icon does not appear do: RunDll32.exe shell32.dll,Control_RunDLL hotplug.dll http://ask-leo.com/safely_remove_hardware_where_did_the_icon_go_how_do_i_safely_remove_hardware_without_it.htmlthanks to all for reply, this code was very helpful RunDll32.exe shell32.dll,Control_RunDLL hotplug.dll |
|
| 8850. |
Solve : Exclamation Marks [!] in DOS text files cause 'FOR /F' processing problems.? |
|
Answer» I'm using 'FOR /F' to change every occurrence of 'X' to 'Y' in every line of a text file. ST, thanks again for the 2 solutions which you provided -- both of which preserve case sensitivity. Yes, that is correct. The SET command used without quotes ignores trailing spaces, so to be sure that, if %outchar% should happen to be a space, it is added, the quotes are used as you saw. [Update] I tested the batch without quotes in that line, and it seems to work just the same. I think I just assumed you needed them. ST, you warned me, in your initial reply, that "poison characters" embedded in text strings can cause problems when PROCESSING them in batch scripts. Sure enough, when my test text file was modified to contain ampersands [&], percent signs [%], and double quotes ["], in ADDITION to the dreaded exclamation marks [!], problems were encountered. Sorry to say, all 3 of your solutions -- which worked fine for exclamation marks [!] -- failed when processing the aforementioned additional rogue characters. I think you might be interested in a solution, I have developed, which seems to cope with all of the above "poison characters". It is based on some of your conversion code (but after many experiments with combinations of enabling/disabling delayed expansion, and in or out of sub-routines). I have commented the script as a reminder of how different methods work, or don't work, in certain situations. My input file [Test-myfile.txt] now contains... Code: [Select]Line 01 containing x but not X! Line 02 containing A but not X!Watch this space!x Line 03 containing X but not Y! and another xylophone. Line 3A containing X and 1st percent % sign, 2nd percent % sign, and 3rd percent % sign. Line 3B containing X and just 2 percent % signs. (Here's the 2nd percent % sign). Line 3C containing X and 1st percent ^% sign, 2nd percent ^% sign, and 3rd percent ^% sign. Line 3D containing X and just 2 percent ^% signs. (Here's the 2nd percent ^% sign). Line 04 containing X and Y and another x and a word like axiom. Line 4A containing x and an ampersand & and another & followed by one more & and a percent % sign. Line 4B containing x and an ampersand & on its own. Line 4C containing 2 ampersands -- this one & and this one & as well. Line 05 containing Y but not x; also an upper-case 'X' in single quotes Line 5A containing W but not X; also a lower-case "x" in double quotes Line 06 containing Xxx (but not Yyy): Line 07 containing B and Z and Y~ Line 08 containing Y but not X# Line 09 containing X and Y and another Xylophone My MS-DOS batch code is now as follows... Code: [Select]@ECHO OFF REM ==================================================== REM Code to change every occurrence of 'X' to 'Y' -- REM in every line of 'Test-myfile.txt' -- without losing -- REM 'special characters'. e.g. [!][%][&][#][~]["][']. REM Preserving upper/lower case is selectable. REM ==================================================== REM Display/obtain case preservation options/choice... ECHO. ECHO When changing 'X' to 'Y' should the original case be preserved? ECHO. ECHO [0] Case-preservation is not important. (Default - Quicker) ECHO [1] Preserve original case. (Slower) ECHO. SET /P CASE_CHOICE=Enter option... ECHO. IF "%CASE_CHOICE%" EQU "1" ECHO Original case will be preserved. (Slower option) IF "%CASE_CHOICE%" NEQ "1" ECHO Original case may not be preserved. (Quicker option) ECHO. PAUSE REM Initialise a count for lines processed. SET LINES_COUNT=0 REM Create an empty Output File. @ECHO OFF > newfile.txt REM One at a time, read each complete line of the Input File into a single string. FOR /F "tokens=1* delims=" %%a in (Test-myfile.txt) DO ( REM ECHO Original line..."%%a" REM At this point, complete string is intact. REM Copy the complete intact string -- REM enclosing in quotes to protect special characters (most). SET string1="%%a" REM At this point, string1 contains the complete intact quoted string -- REM but appears to be empty/undefined if echoed. REM For each line of the Input File, string processing requires 'EnableDelayedExpansion' -- REM which can only be executed a maximum of 16 times before reaching the -- REM 'Maximum setlocal recursion level' (despite also executing 'DisableDelayedExpansion'). REM Also, within 'EnableDelayedExpansion' %%a will lose exclamation marks -- REM fortunately we no longer need %%a (for the current line) as it has been copied to string1. REM For these reasons, the main string processing is done in a subroutine... CALL :REPLACE_CHARS ) ENDLOCAL ECHO Done! PAUSE EXIT :REPLACE_CHARS REM Increment lines processed count... SET /A LINES_COUNT=%LINES_COUNT%+1% REM Enable delayed environment variable expansion -- REM so that the value of certain variables can be dynamically redefined at run time -- REM using !Variable! instead of %Variable% (or a combination)... SETLOCAL EnableDelayedExpansion REM Display progress... ECHO Original Line !LINES_COUNT! ...!string1!... REM At this point, string1 still contains the complete intact quoted string. REM Ascertain whether preservation of original case is required... IF "!CASE_CHOICE!" EQU "1" GOTO PRESERVE_CASE REM Original case is not required to be preserved... REM Convert all 'X's in the string (line) to 'Y's -- REM upper and lower-case 'X's will be converted to upper-case 'Y's. SET string2=!string1:X=Y! GOTO WRITE_LINE REM Original case must be preserved... :PRESERVE_CASE REM Initialise an index for the current character position -- REM and an empty string to construct the converted line... set j=0 set string2= :Loop REM One at a time, isolate each individual character in the string (line)... set inchar=!string1:~%j%,1%! IF "!inchar!END"=="END" GOTO :ExitLoop REM Copy the current character for passing to the modified string (line)... SET outchar=!inchar! REM Convert 'X's to 'Y's -- preserving the original case... IF "!inchar!"=="X" set outchar=Y IF "!inchar!"=="x" set outchar=y REM Construct the new string (line) by concatenating the current/modified character... SET "string2=!string2!!outchar%!" REM Increment the index for the next character position, and repeat... SET /A j=!j!+1% GOTO :Loop :ExitLoop :WRITE_LINE REM Strip-off the leading/trailing quotes from the processed string (line) -- REM then write it to the Output File -- ensuring no spaces are added at end of line. ECHO !string2:~1,-1!>> newfile.txt REM Display progress... ECHO Modified Line !LINES_COUNT! ...!string2!... REM Disable delayed environment variable expansion. SETLOCAL DisableDelayedExpansion REM Return whence we came. GOTO :EOFQuote REM For each line of the Input File, string processing requires 'EnableDelayedExpansion' -- I'm not sure what you mean by this - you only enable delayed expansion once, at any point before the loop or other structure. You don't have to re-enable it for each line that is read from a file! Isn't this better? Sooner or later if you are doing SERIOUS textfile processing you are going to need to look at something else. Visual Basic Script is present in every Windows installation these days. Save as a .vbs file and run with Cscript //nologo yourname.vbs Code: [Select]Set fso = CreateObject("Scripting.FileSystemObject") Const ForReading = 1, ForWriting = 2, ForAppending = 8 Const FormatSystemDefault = -2, FormatUnicode = -1, FormatASCII = 0 ReadfileName ="Input.txt" WriteFileName="Output.txt" Wscript.echo "Read file..." Set InputFile = fso.openTextFile (ReadFileName, ForReading, FormatASCII) Set OutputFile = fso.openTextFile (WriteFileName, ForWriting, FormatASCII) Do While Not InputFile.AtEndOfStream InputLine = InputFile.readline Wscript.Echo "Input " & InputLine TempLine = InputLine TempLine = Replace(TempLine, "X", "Y") TempLine = Replace(TempLine, "x", "y") OutputLine = TempLine Wscript.Echo "Output " & OutputLine OutputFile.WriteLine(OutputLine) Loop InputFile.Close Outputfile.Close Set fso = Nothing Set Shell = Nothing |
|