Find, Copy and Rename in BATCH

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
kalinkula
Posts: 1
Joined: 22 Jun 2018 05:21

Find, Copy and Rename in BATCH

#1 Post by kalinkula » 22 Jun 2018 05:22

Good Morning!

Coming from another article, which i tried to adopt, but failed, i would like to ask my question here. I need to achieve two things:

Copy all files that contain a certain string in their filename from one directory to another, but only if that file does not already exists in that target directory. The filename could be something like "EventLog_12345.txt" and i would want to copy only the files where the filename contains "EventLog".

In a set of files identify in every .txt file a certain string. This string indicates the line that contains the string i am looking for. I want to get to the end of this line and save the .txt file as a new .txt file with a new name based on the string i find at the end of this line. Example: My file is "EventLog_12345.txt" and somewhere in this file there is a line like this:

2018-06-22 08:21:19 0133 LET vVariable = 'h**ps://somedomain.com/test/1/2/4/jobs/joblog.XML'

The string indicating the line is vVariable. The string i want to use within the new filename in this example is joblog.xml. The file should be stored as a new .txt file with the name: joblog_12345.txt. Note, that the length of the line can vary; so can the length of the domain string; also the names of the XMLs are different. The constant is that i always want to have the name of the XML file which is always the last piece of the domain.

I hope someone can help me with this! Thanks in advance.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Find, Copy and Rename in BATCH

#2 Post by dbenham » 22 Jun 2018 08:34

Your description of your requirements is a bit convoluted. But I think this is what you want:

Code: Select all

@echo off
setlocal

:: CHANGE THESE DEFINITIONS TO MATCH YOUR ACTUAL FOLDER PATHS
set "src=c:\sourceFolder"
set "dst=c:\destinationFolder"

pushd "%src%"
for /f "delims=: tokens=1*" %%A in (
  'findstr vVariable EventLog*.txt'
) do if not exist "%dst%\%%~nB.txt" copy "%%A" "%dst%\%%~nB.txt"
popd
It uses FINDSTR to scan all txt files with a name that begins with EventLog, and output each line that contains vVariable, prefixing each line with the source file name followed by a colon.

FOR /F is used to parse the source file name and the target name from the FINDSTR output, and then the file is copied to the destination with the new name if and only if the new name does not already exist.

Dave Benham

Post Reply