Computer Forums

Member Login

Remember Me? Sign Up! | Forgot Password
 
Slogan
 
Closed Thread
Old 11-06-2008, 11:01 AM   #1 (permalink)
 
Newb Techie

Join Date: Nov 2008

Posts: 4

under_score is on a distinguished road

Default batch to copy file help

Okay, I'm having a slight problem. This code:

Code:
@echo off
setLocal EnableDelayedExpansion

for /f "tokens=* delims= " %%a in ('dir/b/a-d') do (
set /a N+=1
echo F|xcopy /y %%a n:\backup\%%~Na!N!%%~Xa
)
copies the file and appends the sequence number. However, I want to sort through file names and also rename them in addition to adding the sequence number. For instance, lets say I have a folder full of files named abc.timestamp.xls, def.timestamp.xls, and xyz.timestamp.xls. I only want to copy xyz.timestamp.xls and I want to copy it over as xyza.sequencenumber.xls. It seems there should be a way to do this but I don't understand the code well enough. What is this code doing? %%~Na!N!%%~Xa

Can anyone help?

Thanks,

Tim

Last edited by Mak213; 11-06-2008 at 12:59 PM.
under_score is offline  
Old 11-06-2008, 02:12 PM   #2 (permalink)
office politics's Avatar
 
It's all just 1s and 0s

Join Date: Jan 2004

Location: in the lab

Posts: 4,410

office politics will become famous soon enough

Default Re: batch to copy file help

where did you get this?

it doesn;t look like a typical batch file. it looks like a combination of batch file and vbscript.


the orignal owner may have a exe named for, but i've never seen it



as far as copying with new sequence numbers, i used to use namedate.exe. i've attached it to this message. you will need to erase the jpg extension...the file is an exe. I don't remember the syntax though.






edit: yea the site won't let me upload the file....here's a link NAMEDATE: Add a date to a given filename

Last edited by office politics; 11-06-2008 at 02:14 PM.
office politics is offline  
Old 11-06-2008, 03:53 PM   #3 (permalink)
 
Newb Techie

Join Date: Nov 2008

Posts: 4

under_score is on a distinguished road

Default Re: batch to copy file help

It is a hybrid script I believe with wmi. third party software is not an option. The code works as is in batch but I need it to be more robust. If I could somehow replace the copy command with xcopy I could get it to work.
under_score is offline  
Old 11-06-2008, 05:25 PM   #4 (permalink)
office politics's Avatar
 
It's all just 1s and 0s

Join Date: Jan 2004

Location: in the lab

Posts: 4,410

office politics will become famous soon enough

Default Re: batch to copy file help

i've never seen anything like this before. it seems xp is updated with some new commands.

can you post a list of name in the backup directory? I'm having trouble figuring out what the destination files are being named.

it seems dir/b/a-d is being run. each line of out put is being saved in variable %%a. The Set /a command looks like a counter for the N variable.

echo gets piped into xcopy. xcopy copies the %%a file to n:\backup with a new filename; %%~Na!N!%%~Xa



here's some info on the commands



FOR command
Code:
Runs a specified command for each file in a set of files.

FOR %variable IN (set) DO command [command-parameters]

  %variable  Specifies a single letter replaceable parameter.
  (set)      Specifies a set of one or more files.  Wildcards may be used.
  command    Specifies the command to carry out for each file.
  command-parameters
             Specifies parameters or switches for the specified command.

To use the FOR command in a batch program, specify %%variable instead
of %variable.  Variable names are case sensitive, so %i is different
from %I.

If Command Extensions are enabled, the following additional
forms of the FOR command are supported:

FOR /D %variable IN (set) DO command [command-parameters]

    If set contains wildcards, then specifies to match against directory
    names instead of file names.

FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]

    Walks the directory tree rooted at [drive:]path, executing the FOR
    statement in each directory of the tree.  If no directory
    specification is specified after /R then the current directory is
    assumed.  If set is just a single period (.) character then it
    will just enumerate the directory tree.

FOR /L %variable IN (start,step,end) DO command [command-parameters]

    The set is a sequence of numbers from start to end, by step amount.
    So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would
    generate the sequence (5 4 3 2 1)

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

    or, if usebackq option present:

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]

    filenameset is one or more file names.  Each file is opened, read
    and processed before going on to the next file in filenameset.
    Processing consists of reading in the file, breaking it up into
    individual lines of text and then parsing each line into zero or
    more tokens.  The body of the for loop is then called with the
    variable value(s) set to the found token string(s).  By default, /F
    passes the first blank separated token from each line of each file.
    Blank lines are skipped.  You can override the default parsing
    behavior by specifying the optional "options" parameter.  This
    is a quoted string which contains one or more keywords to specify
    different parsing options.  The keywords are:

        eol=c           - specifies an end of line comment character
                          (just one)
        skip=n          - specifies the number of lines to skip at the
                          beginning of the file.
        delims=xxx      - specifies a delimiter set.  This replaces the
                          default delimiter set of space and tab.
        tokens=x,y,m-n  - specifies which tokens from each line are to
                          be passed to the for body for each iteration.
                          This will cause additional variable names to
                          be allocated.  The m-n form is a range,
                          specifying the mth through the nth tokens.  If
                          the last character in the tokens= string is an
                          asterisk, then an additional variable is
                          allocated and receives the remaining text on
                          the line after the last token parsed.
        usebackq        - specifies that the new semantics are in force,
                          where a back quoted string is executed as a
                          command and a single quoted string is a
                          literal string command and allows the use of
                          double quotes to quote file names in
                          filenameset.

    Some examples might help:

FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k

    would parse each line in myfile.txt, ignoring lines that begin with
    a semicolon, passing the 2nd and 3rd token from each line to the for
    body, with tokens delimited by commas and/or spaces.  Notice the for
    body statements reference %i to get the 2nd token, %j to get the
    3rd token, and %k to get all remaining tokens after the 3rd.  For
    file names that contain spaces, you need to quote the filenames with
    double quotes.  In order to use double quotes in this manner, you also
    need to use the usebackq option, otherwise the double quotes will be
    interpreted as defining a literal string to parse.

    %i is explicitly declared in the for statement and the %j and %k
    are implicitly declared via the tokens= option.  You can specify up
    to 26 tokens via the tokens= line, provided it does not cause an
    attempt to declare a variable higher than the letter 'z' or 'Z'.
    Remember, FOR variables are single-letter, case sensitive, global, 
    and you can't have more than 52 total active at any one time.

    You can also use the FOR /F parsing logic on an immediate string, by
    making the filenameset between the parenthesis a quoted string,
    using single quote characters.  It will be treated as a single line
    of input from a file and parsed.

    Finally, you can use the FOR /F command to parse the output of a
    command.  You do this by making the filenameset between the
    parenthesis a back quoted string.  It will be treated as a command
    line, which is passed to a child CMD.EXE and the output is captured
    into memory and parsed as if it was a file.  So the following
    example:

      FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i

    would enumerate the environment variable names in the current
    environment.

In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path name
    %~dI        - expands %I to a drive letter only
    %~pI        - expands %I to a path only
    %~nI        - expands %I to a file name only
    %~xI        - expands %I to a file extension only
    %~sI        - expanded path contains short names only
    %~aI        - expands %I to file attributes of file
    %~tI        - expands %I to date/time of file
    %~zI        - expands %I to size of file
    %~$PATH:I   - searches the directories listed in the PATH
                   environment variable and expands %I to the
                   fully qualified name of the first one found.
                   If the environment variable name is not
                   defined or the file is not found by the
                   search, then this modifier expands to the
                   empty string

The modifiers can be combined to get compound results:

    %~dpI       - expands %I to a drive letter and path only
    %~nxI       - expands %I to a file name and extension only
    %~fsI       - expands %I to a full path name with short names only
    %~dp$PATH:I - searches the directories listed in the PATH
                   environment variable for %I and expands to the
                   drive letter and path of the first one found.
    %~ftzaI     - expands %I to a DIR like output line

In the above examples %I and PATH can be replaced by other valid
values.  The %~ syntax is terminated by a valid FOR variable name.
Picking upper case variable names like %I makes it more readable and
avoids confusion with the modifiers, which are not case sensitive.


SET command
Code:
Displays, sets, or removes cmd.exe environment variables.

SET [variable=[string]]

  variable  Specifies the environment-variable name.
  string    Specifies a series of characters to assign to the variable.

Type SET without parameters to display the current environment variables.

If Command Extensions are enabled SET changes as follows:

SET command invoked with just a variable name, no equal sign or value
will display the value of all variables whose prefix matches the name
given to the SET command.  For example:

    SET P

would display all variables that begin with the letter 'P'

SET command will set the ERRORLEVEL to 1 if the variable name is not
found in the current environment.

SET command will not allow an equal sign to be part of the name of
a variable.

Two new switches have been added to the SET command:

    SET /A expression
    SET /P variable=[promptString]

The /A switch specifies that the string to the right of the equal sign
is a numerical expression that is evaluated.  The expression evaluator
is pretty simple and supports the following operations, in decreasing
order of precedence:

    ()                  - grouping
    ! ~ -               - unary operators
    * / %               - arithmetic operators
    + -                 - arithmetic operators
    << >>               - logical shift
    &                   - bitwise and
    ^                   - bitwise exclusive or
    |                   - bitwise or
    = *= /= %= += -=    - assignment
      &= ^= |= <<= >>=
    ,                   - expression separator

If you use any of the logical or modulus operators, you will need to
enclose the expression string in quotes.  Any non-numeric strings in the
expression are treated as environment variable names whose values are
converted to numbers before using them.  If an environment variable name
is specified but is not defined in the current environment, then a value
of zero is used.  This allows you to do arithmetic with environment
variable values without having to type all those % signs to get their
values.  If SET /A is executed from the command line outside of a
command script, then it displays the final value of the expression.  The
assignment operator requires an environment variable name to the left of
the assignment operator.  Numeric values are decimal numbers, unless
prefixed by 0x for hexadecimal numbers, and 0 for octal numbers.
So 0x12 is the same as 18 is the same as 022. Please note that the octal
notation can be confusing: 08 and 09 are not valid numbers because 8 and
9 are not valid octal digits.

The /P switch allows you to set the value of a variable to a line of input
entered by the user.  Displays the specified promptString before reading
the line of input.  The promptString can be empty.

Environment variable substitution has been enhanced as follows:

    %PATH:str1=str2%

would expand the PATH environment variable, substituting each occurrence
of "str1" in the expanded result with "str2".  "str2" can be the empty
string to effectively delete all occurrences of "str1" from the expanded
output.  "str1" can begin with an asterisk, in which case it will match
everything from the beginning of the expanded output to the first
occurrence of the remaining portion of str1.

May also specify substrings for an expansion.

    %PATH:~10,5%

would expand the PATH environment variable, and then use only the 5
characters that begin at the 11th (offset 10) character of the expanded
result.  If the length is not specified, then it defaults to the
remainder of the variable value.  If either number (offset or length) is
negative, then the number used is the length of the environment variable
value added to the offset or length specified.

    %PATH:~-10%

would extract the last 10 characters of the PATH variable.

    %PATH:~0,-2%

would extract all but the last 2 characters of the PATH variable.

Finally, support for delayed environment variable expansion has been
added.  This support is always disabled by default, but may be
enabled/disabled via the /V command line switch to CMD.EXE.  See CMD /?

Delayed environment variable expansion is useful for getting around
the limitations of the current expansion which happens when a line
of text is read, not when it is executed.  The following example
demonstrates the problem with immediate variable expansion:

    set VAR=before
    if "%VAR%" == "before" (
        set VAR=after
        if "%VAR%" == "after" @echo If you see this, it worked
    )

would never display the message, since the %VAR% in BOTH IF statements
is substituted when the first IF statement is read, since it logically
includes the body of the IF, which is a compound statement.  So the
IF inside the compound statement is really comparing "before" with
"after" which will never be equal.  Similarly, the following example
will not work as expected:

    set LIST=
    for %i in (*) do set LIST=%LIST% %i
    echo %LIST%

in that it will NOT build up a list of files in the current directory,
but instead will just set the LIST variable to the last file found.
Again, this is because the %LIST% is expanded just once when the
FOR statement is read, and at that time the LIST variable is empty.
So the actual FOR loop we are executing is:

    for %i in (*) do set LIST= %i

which just keeps setting LIST to the last file found.

Delayed environment variable expansion allows you to use a different
character (the exclamation mark) to expand environment variables at
execution time.  If delayed variable expansion is enabled, the above
examples could be written as follows to work as intended:

    set VAR=before
    if "%VAR%" == "before" (
        set VAR=after
        if "!VAR!" == "after" @echo If you see this, it worked
    )

    set LIST=
    for %i in (*) do set LIST=!LIST! %i
    echo %LIST%

If Command Extensions are enabled, then there are several dynamic
environment variables that can be expanded but which don't show up in
the list of variables displayed by SET.  These variable values are
computed dynamically each time the value of the variable is expanded.
If the user explicitly defines a variable with one of these names, then
that definition will override the dynamic one described below:

%CD% - expands to the current directory string.

%DATE% - expands to current date using same format as DATE command.

%TIME% - expands to current time using same format as TIME command.

%RANDOM% - expands to a random decimal number between 0 and 32767.

%ERRORLEVEL% - expands to the current ERRORLEVEL value

%CMDEXTVERSION% - expands to the current Command Processor Extensions
    version number.

%CMDCMDLINE% - expands to the original command line that invoked the
    Command Processor.

office politics is offline  
Old 11-07-2008, 11:34 AM   #5 (permalink)
 
Newb Techie

Join Date: Nov 2008

Posts: 4

under_score is on a distinguished road

Default Re: batch to copy file help

Okay, let's forget about that code for a second and explore other options.

Here is the script that I run daily to copy files that are written throughout the day over to a new folder:

code:
Code:
for /F "tokens=1-2 delims= " %%a in ("%date%") do set xdate=%%b

for /f "tokens=1-5 delims=:" %%d in ("%time%") do ECHO F|xcopy /y E:\share\ASampleLog*.* N:\backup\"XYZ.%%d%%e%%f.xls" /D:%xdate%

for /f "tokens=1-5 delims=:" %%d in ("%time%") do ECHO F|xcopy /y E:\share\BSampleLog*.* N:\backup\"XYZ.%%d%%e%%f.xls" /D:%xdate%

for /f "tokens=1-5 delims=:" %%d in ("%time%") do ECHO F|xcopy /y E:\share\CSampleLog*.* N:\backup\"XYZ.%%d%%e%%f.xls" /D:%xdate%
The above code captures all incremental files written on a daily basis. However, I also have 18 months worth of files that I want to move over using a similar format. I want it to go through all of the files and find the ones that start with the ASampleLog file name and copy and rename them to XYZ.timestamp.xls. The timestamp is just an example. The main thing I need to do is just have them get a unique name so that they don't overwrite each other.

Is there a way to do this using xcopy or other?

Thanks

Last edited by under_score; 11-07-2008 at 11:36 AM.
under_score is offline  
Old 11-07-2008, 05:19 PM   #6 (permalink)
office politics's Avatar
 
It's all just 1s and 0s

Join Date: Jan 2004

Location: in the lab

Posts: 4,410

office politics will become famous soon enough

Default Re: batch to copy file help

you could prolly use a single xcopy command if the time variable didn't have colons in it. a filename cannot have a colon in it.



i went ahead and did this in vbscript as i can write code quicker with it

save this as vbs. change the first three variables as needed. i think they are self explainitory. This hasnt been tested

Code:
prefix = "ASampleLog"

destfold = "c:\new\"

srcfold = "c:\"

Dim filesys, demofolder, fil, filecoll, filist 
Set filesys = CreateObject("Scripting.FileSystemObject") 
if filesys.folderexists(destfold) then
Set demofolder = filesys.GetFolder(srcfold) 
Set filecoll = demofolder.Files 
cnt = 0
For Each fil in filecoll 
if left(fil.name,len(prefix)) = prefix then
fil.Copy(destfold & cnt & fil.name)
cnt = cnt + 1 
end if
Next 
else 
msgbox destfold & "does not exist"
end if

office politics is offline  
Old 11-14-2008, 08:38 AM   #7 (permalink)
 
Newb Techie

Join Date: Nov 2008

Posts: 4

under_score is on a distinguished road

Default Re: batch to copy file help

OP, sorry for the delay. I've been in training all week. I'll give this a try and get back with you.
under_score is offline  
 
Closed Thread

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Installing Ubuntu. 95BlackGA Linux, BSD, other *nixes & Open Source Software 1 10-16-2008 09:44 PM
A sneaky, and annoying virus donaldj HijackThis Logs (finished) 25 06-16-2008 08:58 PM
Possible Corrupted/Infected Files. xXxexpertxXx Virus - Spyware Protection / Detection 11 03-12-2008 01:18 AM
WTF is a Bad Block? MikesCreation Hardware Troubleshooting 18 02-24-2008 09:31 PM
Another Hijack Log boo HijackThis Logs (finished) 17 06-26-2007 12:30 PM