Copy files with particular string non zero batch - windows

I'm trying to copy all the logs that have a non-zero value on a certain string (can be in different lines) to be copied to a folder. Right now I a batch file that can copy based on a set value, I want it to be copied for any non-zero value. What do I need to modify to copy only files of non-zero. Maybe set the string to search for the zero "Errors 0" and if found don't copy.
setlocal enabledelayedexpansion
for %%a in (*.LOG) do (
set found=false
for /f "skip=2 tokens=*" %%b in ('find "Errors 1" "%%a"') do (
if "!found!"=="false" (
echo %%a >>output.txt
copy %%a %OLDDIR%\output\sv1
set found=true
)
)
)

try this:
#echo on &setlocal
for %%a in (*.LOG) do (
find "Errors 0" "%%~a" || copy "%%~a" "%OLDDIR%\output\sv1"
)
|| if fail, process the next command
&& if success, process the next command

Related

Create a .bat file based on common column and out put will be selective column

I am completely new to .bat code. I want to merge two csv file based on common column and selective columns for the output file.
For ex
file1.csv
id,name,roll
1,x,12
2,y,13
file2.csv
id,class,subject
1,V,english
2,III,Math
Output will be
result.csv
id,name,class,subject
1,x,V,english
2,y,III,Math
Below is the code I started. My problem is how to use the common column and select the column.
#echo off
set "tmpfile=%temp%\result.tmp"
set "csvfile=result.csv"
copy nul "%tmpfile%" >nul
echo.
echo Processing all CSV files...
set "header="
for %%a in (%1) do (
if not "%%a"=="%csvfile%" (
set /p =Processing %%a...<nul
for /f "tokens=1* usebackq delims=," %%b in ("%%a") do (
if /i "%%b"=="Keyword" (
if not defined header (
set /p =Found header...<nul
set "header=%%b,%%c"
)
) else (
title [%%a] - %%b,%%c
findstr /b /c:"%%b" /i "%tmpfile%">nul || echo %%b,%%c>>"%tmpfile%"
)
)
echo OK
)
)
echo Finished processing all CSV files
echo.
echo Creating %csvfile%
echo %header%>"%csvfile%"
set /p =Sorting data...<nul
sort "%tmpfile%">>"%csvfile%"
echo OK
del "%tmpfile%"
echo Finished!
title Command Prompt
exit /b
The problem description lacks multiple details and the example code provided has no relation to the description. In the description you talk about two files but in the code you process "all CVS files" with no indication of which "two files" should be merged. The code has an undescribed "Keyword" value. The code sorts the output file, but this is not necessary because "both input files are sorted by common column" as you said...
Anyway I tried to help you writting a working code that achieve what you said in the problem description. I searched for "file merge" in the Batch-file tag and get multiple results, so I just used this method as base...
#echo off
setlocal EnableDelayedExpansion
set "Header1="
set "Header2="
set "common2=-999999999"
rem Read second file from redirected input
< file2.csv (
rem Read first file via FOR /F
for /F "tokens=1,2 delims=," %%a in (file1.csv) do (
if not defined Header1 (
set "Header1=%%a,%%b"
) else (
if !common2! lss %%a call :ReadNextFile2RecordUntil %%a
if !common2! equ %%a echo %%a,%%b,!rest2!
)
)
) > result.csv
goto :EOF
:ReadNextFile2RecordUntil commonCol
set "line2="
set /P "line2="
if not defined line2 set "common2=999999999" & exit /B
for /F "tokens=1* delims=," %%A in ("%line2%") do (
if not defined Header2 (
set "Header2=%%B"
echo %Header1%,%%B
goto ReadNextFile2RecordUntil %1
) else (
set "common2=%%A"
set "rest2=%%B"
)
)
if !common2! lss %1 goto ReadNextFile2RecordUntil %1
exit /B
file1:
id,name,roll
1,x,12
2,y,13
4,z,record1 with no matching record2
5,t,15
file2.csv:
id,class,subject
1,V,english
2,III,Math
3,IV,record2 with no matching record1
5,V,OK
result.csv:
id,name,class,subject
1,x,V,english
2,y,III,Math
5,t,V,OK

Trouble getting a moving script to read filename and perform actions based on this

I am trying to get a mover batch script to read the filenames in a folder and do things to them based on the filename before moving them.
I have no trouble getting the files to be moved but I can't get the doing stuff based on filename part right.
#ECHO on
setlocal enableDelayedExpansion
SET src_folder=c:\recordz
SET tar_folder=\\TOWER\Temprec
:LOOP
for /f "delims=" %%a IN ('dir "%src_folder%"\*.mpg /b') do (
set "var=%%~na"
Echo %var%
Rem this part is supposed to check if NFL is part of the filename
If NOT "%var%"=="%var:NFL=%" (
echo Found inside
REN "%src_folder%\%%~na.mpg" "%%~na.ts"
move %src_folder%\"%%~na.ts" %tar_folder%
) else (
echo No cigar
move %src_folder%\"%%~na.mpg" %tar_folder%
)
)
REM Crafty 5 minute delay...
PING 1.1.1.1 -n 1 -w 1800000 >NUL
GOTO LOOP
When I run the above, I get this:
C:\Scripts>(
set "var=Feux_20161003_21002200"
Echo
If NOT "" == "NFL=" (
echo Found inside
REN "c:\recordz\Feux_20161003_21002200.mpg" "Feux_20161003_21002200.ts"
move c:\recordz\"Feux_20161003_21002200.ts" \\TOWER\Temprec
) else (
echo No cigar
move c:\recordz\"Feux_20161003_21002200.mpg" \\TOWER\Temprec
)
)
ECHO is on.
Found inside
Although you have enabled the delayed expansion you are not using it. Change % to ! inside the loop.
for /f "delims=" %%a IN ('dir "%src_folder%"\*.mpg /b') do (
set var=%%~na
Echo !var!
Rem this part is supposed to check if NFL is part of the filename
If NOT "!var!"=="!var:NFL=!" (
echo Found inside
REN "%src_folder%\%%~na.mpg" "%%~na.ts"
move %src_folder%\"%%~na.ts" %tar_folder%
) else (
echo No cigar
move %src_folder%\"%%~na.mpg" %tar_folder%
)
)

Find string in multiple .txt files

I have a folder with many .txt files. I would like to find string "X" in all of these files then I would like to copy the found strings into .txt files into a different folder.
So far I have tried :
#echo on
findstr /m "X" "%userprofile%\Desktop\New_Folder\New_Folder\*.txt"
if %errorlevel%==0 do (
for %%c in (*.txt) do (
type %%c >> "%UserProfile%\Desktop\New_Folder\%%~nc.txt"
pause
I do not understand the output %%~nc.txt part it's suppost to copy the changed .txt files to a new folder with the same name.
I would like to point out that string "X" is found in different places in the .txt file.
This batch file can did the trick (-_°)
So, just give a try : ScanfilesWordSearch_X.bat
#ECHO OFF
::******************************************************************************************
Title Scan a folder and store all files names in an array variables
SET "ROOT=%userprofile%\Desktop"
Set "NewFolder2Copy=%userprofile%\Desktop\NewCopyTxtFiles"
SET "EXT=txt"
SET "Count=0"
Set "LogFile=%~dp0%~n0.txt"
set "Word2Search=X"
SETLOCAL enabledelayedexpansion
REM Iterates throw the files on this current folder and its subfolders.
REM And Populate the array with existent files in this folder and its subfolders
For %%a in (%EXT%) Do (
Call :Scanning "%Word2Search%" "*.%%a"
FOR /f "delims=" %%f IN ('dir /b /s "%ROOT%\*.%%a"') DO (
( find /I "%Word2Search%" "%%f" >nul 2>&1 ) && (
SET /a "Count+=1"
set "list[!Count!]=%%~nxf"
set "listpath[!Count!]=%%~dpFf"
)
) || (
( Call :Scanning "%Word2Search%" "%%~nxf")
)
)
::***************************************************************
:Display_Results
cls & color 0B
echo wscript.echo Len("%ROOT%"^) + 20 >"%tmp%\length.vbs"
for /f %%a in ('Cscript /nologo "%tmp%\length.vbs"') do ( set "cols=%%a")
If %cols% LSS 50 set /a cols=%cols% + 20
set /a lines=%Count% + 10
Mode con cols=%cols% lines=%lines%
ECHO **********************************************************
ECHO Folder:"%ROOT%"
ECHO **********************************************************
If Exist "%LogFile%" Del "%LogFile%"
rem Display array elements and save results into the LogFile
for /L %%i in (1,1,%Count%) do (
echo [%%i] : !list[%%i]!
echo [%%i] : !list[%%i]! -- "!listpath[%%i]!" >> "%LogFile%"
)
(
ECHO.
ECHO Total of [%EXT%] files(s^) : %Count% file(s^) that contains the string "%Word2Search%"
)>> "%LogFile%"
ECHO(
ECHO Total of [%EXT%] files(s) : %Count% file(s)
echo(
echo Type the number of file that you want to explore
echo(
echo To save those files just hit 'S'
set /p "Input="
For /L %%i in (1,1,%Count%) Do (
If "%INPUT%" EQU "%%i" (
Call :Explorer "!listpath[%%i]!"
)
IF /I "%INPUT%"=="S" (
Call :CopyFiles
)
)
Goto:Display_Results
::**************************************************************
:Scanning <Word> <file>
mode con cols=75 lines=3
Cls & Color 0E
echo(
echo Scanning for the string "%~1" on "%~2" ...
goto :eof
::*************************************************************
:Explorer <file>
explorer.exe /e,/select,"%~1"
Goto :EOF
::*************************************************************
:MakeCopy <Source> <Target>
If Not Exist "%~2\" MD "%~2\"
Copy /Y "%~1" "%~2\"
goto :eof
::*************************************************************
:CopyFiles
cls
mode con cols=80 lines=20
for /L %%i in (1,1,%Count%) do (
echo Copying "!list[%%i]!" "%NewFolder2Copy%\"
Call :MakeCopy "!listpath[%%i]!" "%NewFolder2Copy%">nul 2>&1
)
Call :Explorer "%NewFolder2Copy%\"
Goto:Display_Results
::*************************************************************
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "mystring=x"
FOR %%a IN ("%sourcedir%\*.txt") DO FINDSTR "%mystring%" "%%a">nul&IF NOT ERRORLEVEL 1 FINDSTR "%mystring%" "%%a">"%destdir%\%%~nxa"
GOTO :EOF
You would need to change the settings of sourcedir and destdir to suit your circumstances and set mystring appropriately, noting that you may have to adjust the findstr switches to accomodate case, literal and space-in-target-string.
Naturally, you could code sourcedir etc. directly as literals, but doing it this way means that the relevant strings need only be changed in one place.
You are close, but checking the ErrorLevel of findstr does not make sense here as this reflects the overall result, that is, ErrorLevel is set to 0 in case any of the files contain the search string.
I would parse the output of findstr /M using a for /F loop and copy the returned files in the body:
for /F "eol=| delims=" %%F in ('
findstr /M /I /C:"X" "%USERPROFILE%\Desktop\New_Folder\New_Folder\*.txt"
') do (
copy "%%F" "%USERPROFILE%\Desktop\New_Folder\"
)
This copies all those files which contain the literal search string (in a case-insensitive manner).

Windows batch file to find duplicates in a tree

I need a batch file ( Windows CMD is the interpreter, a .bat ) to do this type of task:
1) Search through a folder and its subfolders
2) Find files with the same filename and extension ( aka duplicates )
3) Check if they have the same size
4) If same name + same size, echo all the files except the first one ( practically I need to delete all except one copy )
Thanks for any type of help
This is only an initial script, just for check the files, in a folder and its subfolders, and their size:
#Echo off
Setlocal EnableDelayedExpansion
Set Dir=C:\NewFolder
For /r "%Dir%" %%i in (*) do (
Set FileName=%%~nxi
Set FullPath=%%i
Set Size=%%~zi
Echo "!FullPath!" - SIZE: !Size!
)
Echo.
Pause
This script does what you ask. Just set the ROOT variable at the top to point to the root of your tree.
#echo off
setlocal disableDelayedExpansion
set root="c:\test"
set "prevTest=none"
set "prevFile=none"
for /f "tokens=1-3 delims=:" %%A in (
'"(for /r "%root%" %%F in (*) do #echo %%~znxF:%%~fF:)|sort"'
) do (
set "currTest=%%A"
set "currFile=%%B:%%C"
setlocal enableDelayedExpansion
if !currTest! equ !prevTest! echo "!currFile!"
endlocal
set "prevTest=%%A"
)
But you can make the test more precise by using FC to compare the contents of the files. Also, you can incorporate the DEL command directly in the script. The script below prints out the commands that would delete the duplicate files. Remove the ECHO before the DEL command when you are ready to actually delete the files.
#echo off
setlocal disableDelayedExpansion
set root="c:\test"
set "prevTest=none"
set "prevFile=none"
for /f "tokens=1-3 delims=:" %%A in (
'"(for /r "%root%" %%F in (*) do #echo %%~znxF:%%~fF:)|sort"'
) do (
set "currTest=%%A"
set "currFile=%%B:%%C"
setlocal enableDelayedExpansion
set "match="
if !currTest! equ !prevTest! fc /b "!prevFile!" "!currFile!" >nul && set match=1
if defined match (
echo del "!currFile!"
endlocal
) else (
endlocal
set "prevTest=%%A"
set "prevFile=%%B:%%C"
)
)
Both sets of code may seem overly complicated, but it is only because I have structured the code to be robust and avoid problems that can plague simple solutions. For example, ! in file names can cause problems with FOR variables if delayed expansion is enabled, and = in file name causes a problem with npocmoka's solution.
#echo off
setlocal
for /f "tokens=1 delims==" %%# in ('set _') do (
set "%%#="
)
for /r %%a in (*.*) do (
if not defined _%%~nxa%%~za (
set "_%%~nxa%%~za=%%~fa"
) else (
echo %%~fa
)
)
endlocal

Replace a line with another line using IF - Batch file

I am trying to replace a line in load.xml using the lines read from FileList.txt.
Contents of load.xml
<mainheader>
<InFilePath>D:\Data\All_Inputfiles\oldfile.txt</InFilePath>
</mainheader>
FileList.txt
newfile1.txt
newfile2.txt
Expecting the output with each iteration as
<mainheader>
<InFilePath>D:\Data\All_Inputfiles\newfile1.txt</InFilePath>
</mainheader>
and with the next iteration replace newfile1.txt with newfile2.txt. I am able to get original string with the final string but last part of the code is throwing syntax error, i.e. from
for /f "delims=" %%a in (!INTEXTFILE!) do call :Change "%%a" .
Could please help me?
Thanks in advance.
#echo off
SETLOCAL EnableDelayedExpansion
Set AllInputFile= D:\data\FileList.txt
SET INTEXTFILE=C:\c:\load.xml
set OUTTEXTFILE=D:\data\tmp_out.txt
SET BackupPath=D:\data\backupload.xml
Set TempFile=D:\data\tmp.txt
SET DbgFile=D:\data\debuginfo.txt
Del !TempFile!
Del !DbgFile!
Copy !INTEXTFILE! !BackupPath!
:replace
findstr /g "InFilePath" !INTEXTFILE!>!TempFile!
:: set string=" <InFilePath>D:\Data\All_Inputfiles\oldfile.txt</InFilePath>"
set /p string=< !TempFile!
SET PREVFILE_NM=!string:~75,-13!
set FinalreplaceLine=!string!
set TARG_FILE=%~1
REM ECHO "Before Replace FinalreplaceLine "!FinalreplaceLine!>>!DbgFile!
set FinalreplaceLine=!FinalreplaceLine:%PREVFILE_NM%=%TARG_FILE%!
ECHO "string "!string!>>!DbgFile!
ECHO "FinalreplaceLine "!FinalreplaceLine!>>!DbgFile!
::string has source string and FinalreplaceLine has target string to replace
for /f "delims=" %%a in (!INTEXTFILE!) do call :Change "%%a"
exit /b
:Change
set Text=%~1
if "%Text%"=="%string%" (
(echo !FinalreplaceLine!)>> !OUTTEXTFILE!
) else (
(echo !Text!)>> !OUTTEXTFILE!
)
exit /b
Does this work for you?:
#echo off
for /f "usebackq delims=" %%a in ("FileList.txt") do (
call :change "%%a"
type "load.xml"
pause
)
echo done
pause
goto :EOF
:change
(
echo ^<mainheader^>
echo ^<InFilePath^>D:\Data\All_Inputfiles\%~1^</InFilePath^>
echo ^</mainheader^>
) > "load.xml"

Resources