I am making a program that automatically backs up files, stores up to a maximum of five of them, and has an option to restore any of the five files. When the files are backed up, it adds a date and time stamp in the format of YYYYMMDD_HHMMSS_filename.ext. In order to restore the file, it is necessary to first cut out the date stamp.
The method I am currently using to cut the date stamp off of the beginning of the file is as follows.
set VAR=%VAR:~16%
echo %VAR%
The problem being, if the backed up file is called “20120825_140343_file name.txt”, the above method will only return “file,” omitting anything after the space. The spaces in the file names need to be preserved for them to be recognized by the program using them.
tl;dr I need to cut the string 20120825_140343_file name.txt into just “file name.txt”, but my method just returns “file.”
If delimiters or something would help I could separate the date stamp and file name with a different character, I.E. 20120825_140343-file-name.txt
Your method, though inelegant and inflexible, should work. This tells me that you are not storing the entire filename in
VAR. That is why%var:~16%only results infile, and notfile name.txt. I assume that you assignVARlike this somewhere:You’ll need to either do this:
Or insert double-quotes around the file name when you call your batch file, and then set
varlike this to remove the quotes:That should be enough to get your batch to work.
====================================================
But, to answer the question you actually asked, I’ll show you a method of extracting “file name.txt” from
varthat will work even if there are more or even less than 16 prefix characters.Use the
for /fstatement, specify the 3rd token, with underscores as a delimiter. Here is a self-contained example. (To run from the command-line, change%%xto%x.Just remember, this solution will NOT fix your problem if you do not fix your code to assure your
VARvariable has the entire filename in it.