I encountered the below code online and modified this on my need.
I just wanna ask since i am new to batch file if there is a way to remove duplicate values after the combine.
#echo off
ECHO Set working directory
pushd %~dp0
ECHO Deleting existing combined file
del combined.csv
setlocal ENABLEDELAYEDEXPANSION
set cnt=1
for %%i in (*.csv) do (
if !cnt!==1 (
for /f "delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
) else if %%i NEQ combined.csv (
for /f "skip=1 delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
)
set /a cnt+=1
)
#ECHO OFF
SETLOCAL
ECHO Set working directory
pushd %~dp0
ECHO Deleting existing combined file
del combined.csv
set "flag="
for %%i in (*.csv) do if %%i NEQ combined.csv (
IF DEFINED flag (
findstr /l /x /v /g:combined.csv "%%i">#.vsc
TYPE #.vsc >>combined.csv
) ELSE (
COPY "%%i" combined.csv >nul
SET flag=y
)
)
DEL #.vsc /F /Q
POPD
GOTO :EOF
This may suit you better.
It uses a simple setlocal rather than the delayedexpansion version, initialising flag to empty then setting it within the loop and using if defined which works on the run-time value of flag.
First time through, it simply copies the detected source file to combined.csv and then sets flag to a value so it's ow defined
each other time through, findstr outputs those lines in the source file %%i that /v do not /x exactly match /l literally /g:filename any line in the combined.txt file TO a tempfile I'be nominated as #.vsc (name not important). Then that file is appended to combined.csv
Consequently, provided any particular .csv is free of duplicate lines within itself, the combined.csv will also be free of duplicate lines.
Since the header line is evidently identical in every file, the initial copy of the first file will place the header into combined.csv and hence findstr will neatly exclude it thereafter.
Revision to combat evil unicode:
#ECHO OFF
SETLOCAL
ECHO Set working directory
pushd %~dp0
ECHO Deleting existing combined file
del combined.csv
set "flag="
for %%i in (*.csv) do if %%i NEQ combined.csv (
(FOR /f "delims=" %%j IN ('type "%%i"') DO ECHO %%j)>#.vsc
IF DEFINED flag (
findstr /l /x /v /g:combined.csv "#.vsc" >##.vsc
TYPE ##.vsc>>combined.csv
) ELSE (
REN #.vsc combined.csv
SET flag=y
)
)
DEL #.vsc /F /Q
DEL ##.vsc /F /Q
POPD
GOTO :EOF
I suspect that the problem is using UNICODE within your files. Cutting-and-pasting your data showed that it was unicode.
The for /f... ceremony reads unicode and produces ASCII, hence this version first simply converts to ASCII using your familiar technique then operates on the converted file #.vsc. findstr does not appreciate outputting to the same file as it's attempting to read as /g:, so a further tempfile ##.vsc is used for the findstr output.
Note that the unicode characters between (header) Last modified and date and also elsewhere will be replaced by question-marks.
Related
I’m using the following script to add a revision number to a .stp file. For example: ABS0012033.stp to ABS0012033_rev001.stp. This is working well.
Now I have some files that end with _asm.stp, for example, ABS0012033_asm.stp. How do I need to modify the script that it works for both file types?
Some additional information: There is only one .stp file to be renamed per time and then the .stp file will be moved to another folder. The text file which contains the revision number is temporary and will be deleted after renaming the .stp file.
The current script does remove the last 4 characters from the filename and stores the filename in variable str1. Then it renames the filename with str1 + revision number.
for /F "usebackq tokens=2" %%a IN (`findstr REVISION C:\PUBLISH_WORKSPACE\*.txt`) do (
SET Rev=%%a)
FOR %%S IN ( c:\publish_workspace\*.STP) DO (SET FILE=%%S)
set str1=%file:~21,-4%
ren %file% %str1%_rev%REV%.stp
EXIT
I have tried to implement an IF function in the following script, but it doesn’t work. It doesn’t write str1 when renaming the filename. Any ideas what the problem could be?
for /F "usebackq tokens=2" %%a IN (`findstr REVISION C:\PUBLISH_WORKSPACE\*.txt`) do (
SET Rev=%%a)
FOR %%S IN ( c:\publish_workspace\*.STP) DO (SET FILE=%%S)
echo.%FILE%|findstr /C:"_asm" >nul 2>&1
if not errorlevel 1 (
set str1=%file:~21,-8%
ren %file% %str1%_rev%REV%.stp
) else (
set str1=%file:~21,-4%
ren %file% %str1%_rex%REV%.stp
)
pause
move c:\publish_workspace\*.stp c:\publish_workspace\stp
del c:\publish_workspace\*.txt
EXIT
Sorry, I'm not sure to understand the problem. What about this?
set Rev=ren001
ren ABS???????_asm.stp ABS???????_%Rev%.stp
This answer makes assumptions, those assumptions could have been resolved had you responded to my comment one day ago.
#Echo Off & SetLocal EnableExtensions
PushD "C:\Publish_Workspace" 2>NUL && (Set "Rev=") || GoTo :EOF
For /F "Tokens=1,* Delims=:" %%G In ('%SystemRoot%\System32\findstr.exe "REVISION" "*.txt"') Do Set "Rev=%%H"
If Not Defined Rev GoTo :EOF
For /F Delims^=^ EOL^= %%G In ('Set "PathExt=" ^& %SystemRoot%\System32\where.exe ".":"*.stp" 2^>NUL') Do For /F Delims^=_^ EOL^= %%H In ("%%~nG") Do Ren "%%G" "%%H_rev%Rev:* =%%%~xG"
I am not a tutor, and will not be providing additional explanation, other than to refer you to my comments, and the built-in help information for each command, (commandName /?).
#echo OFF
setlocal EnableExtensions DisableDelayedExpansion
set "FileName=F:\Program Files(x86)\SteamLibrary\steamapps\common\Conan Exiles\ConanSandbox\Config\DefaultGame.ini"
set "TempFile=%TEMP%\%~n0.tmp"
if not exist "%FileName%" goto EndBatch
del "%TempFile%" 2>nul
for /F delims^=^ eol^= %%A in ('%SystemRoot%\System32\findstr.exe /N "^" "%FileName%"') do (
set "Line=%%A"
setlocal EnableDelayedExpansion
if not "!Line:+StartupMovies=StartupUE4!" == "!Line!" (
echo -StartupMovies=StartupUE4
) else if not "!Line:+StartupMovies=StartupNvidia!" == "!Line!" (
echo -StartupMovies=StartupNvidia
) else if not "!Line:+StartupMovies=CinematicIntroV2!" == "!Line!" (
echo -StartupMovies=CinematicIntroV2
) else echo(!Line:*:=!
endlocal
) >>"%TempFile%"
rem Is the temporary file not binary equal the existing INI file, then move
rem the temporary file over existing INI file and delete the temporary file
rem if that fails like on INI file currently opened by an application with
rem no shared write access. Delete the temporary file if it is binary equal
rem the existing INI file because of nothing really changed.
%SystemRoot%\System32\fc.exe /B "%TempFile%" "%FileName%" >nul
if errorlevel 1 (
move /Y "%TempFile%" "%FileName%"
if errorlevel 1 del "%TempFile%"
) else del "%TempFile%"
:EndBatch
endlocal
What it starts with in that ini file
[/Script/MoviePlayer.MoviePlayerSettings]
bWaitForMoviesToComplete=True
bMoviesAreSkippable=True
-StartupMovies=
+StartupMovies=StartupUE4
+StartupMovies=StartupNvidia
+StartupMovies=CinematicIntroV2
What i want it to do
[/Script/MoviePlayer.MoviePlayerSettings]
bWaitForMoviesToComplete=True
bMoviesAreSkippable=True
-StartupMovies=
-StartupMovies=StartupUE4
-StartupMovies=StartupNvidia
-StartupMovies=CinematicIntroV2
What it Really Does
[/Script/MoviePlayer.MoviePlayerSettings]
bWaitForMoviesToComplete=True
bMoviesAreSkippable=True
-StartupMovies=
-StartupMovies=StartupUE4
-StartupMovies=StartupUE4
-StartupMovies=StartupUE4
Me and My Buddy have been at this for a bit this is as close as we have gotten to getting even remotely close before this we had it repeating and replaceing the whole ini file and repeating in a loop now we are just having trouble getting the code to work right and replace all the lines like we want it
Any ideas On How i can Possibly Fix this?
Aaaak! It would probably be easier if you got rid of the if not ... else ... structure. Your double-negatives are very hard to follow.
As for your problem, examine :
"!Line:+StartupMovies=StartupUE4!" == "!Line!"
This will replace any +StartupMovies in line with StartupUE4 and compare the result to the original value of Line
This means that any line containing +StartupMovies will test FALSE. You use a NOT in your if test, so the following echo -StartupMovies=StartupUE4 will be executed for any line which contains +StartupMovies.
Try this:
....
for /F "usebackq delims=" %%A in ("%FileName%") do (
setlocal EnableDelayedExpansion
set "Line=%%A"
set "regurgitate=Y"
if "!Line:+StartupMovies=!" NEQ "!Line!" (
rem a "+StartupMovies" line
for %%s in (StartupUE4 StartupNvidia CinematicIntroV2) do if "!Line:%%s=!" NEQ "!Line!" (
echo -StartupMovies=%%s
set "regurgitate="
)
)
if defined regurgitate echo %%A
endlocal
) >>"%TempFile%"
....
Since filename is quoted (as it has to be assuming its contents may include spaces), then the usebackq modifier tells batch that it is to process the file "%FileName%". The delims= assigns the entire line to %%A.
For each line, regurgitate is set to a non-empty value. Detect the required common string and if that line also includes any of the three strings, then echo the -start... line and set the value of regurgitate to empty
If regurgitate survives the process, then simply echo the original unprocessed line.
Now, if you simply want to change +startup... to -startup... then this is a little shorter:
for /F "usebackq delims=" %%A in ("%FileName%") do (
setlocal EnableDelayedExpansion
set "Line=%%A"
echo !Line:+StartupMovies=-StartupMovies!
endlocal
) >>"%TempFile%"
That is, if the string is found, replace it; otherwise, regurgitate it.
Scenario:
We have multiple releases of a product, and for each release, a folder is created in the main folder. A help file is modified in various releases. I have all the help file names listed in a text file.
I need a script to:
Take each file name from the filenames.txt file
Search for the file by that name in the entire directory (in all releases)
Find the latest file
Copy it to a specified folder
I took help from the various pieces of code I found on Stack Overflow, and combined them to get this code:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
echo.
FOR /F "usebackq delims=" %%a in ("filenames.txt") do (
SET "x=%%a"
ECHO '!x!'
SET FFPath=C:\SVN\nlbavwdocsvn\rep_doc_erpln\trunk\ERPLN
SET NewPath=C:\Lavanya\extracted
SET NewestDate=20160824
ECHO Recursively searching %FFPath%
FOR /F %%I in ('DIR %FFPath%\ !x! /a:-d /s /b') DO (
SET FullDate=%%~tI
ECHO %FFPath%
REM Set CurrDate to yyyymmdd format. Note: Will fail if regional settings changed.
SET CurrDate=!FullDate:~6,4!!FullDate:~0,2!!FullDate:~3,2!
If !CurrDate! gtr !NewestDate! (
SET NewestDate=!CurrDate!
SET NewestFile=%%~fI )
ECHO Copying %NewestFile% to %NewPath%
ECHO.
COPY /Y "%NewestFile%" "%NewPath%"
ECHO.
)
)
PAUSE
This code is not working. And I am unable to figure out the error.
Here is a script to search for the most recently modified file, using the wmic command to retrieve the last modification date/time in a locale-independent manner (e. g., 20160824115500.000000+060).
So for every file name read from the list file .\filenames.txt, the directory tree routed at directory C:\SVN\nlbavwdocsvn\rep_doc_erpln\trunk\ERPLN is searched for matching files recursively, and the respective modify date/time stamp is gathered. Due to its format, a simple greater-than (GTR) comparison can be done do determine whether or not it is a later point of time than a cached one; if the criterion is fulfilled, the cache is updated accordingly.
The upper-case REM and ECHO commands constitute placeholders only for the real action to be performed on the files. Extend the script there as you like. Variable !LASTFILE! holds the full path to each encountered file.
So here is the code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "LOCATION=C:\SVN\nlbavwdocsvn\rep_doc_erpln\trunk\ERPLN"
set "FILELIST=.\filenames.txt"
set "WMICPROP=LastModified" & rem // {CreationDate | LastAccessed | LastModified}
pushd "%LOCATION%" || exit /B 1
for /F "usebackq eol=| delims=" %%L in ("%FILELIST%") do (
set "LASTFILE="
set "LASTFAGE=00000000000000.000000+000"
for /F "eol=| delims=" %%F in ('dir /B /S /A:-D "%%~L"') do (
set "FILE=%%F"
setlocal EnableDelayedExpansion
set "FILE=!FILE:\=\\!"
for /F "tokens=2 delims==" %%J in ('
2^> nul wmic DataFile WHERE ^(Name^="!FILE!"^) GET %WMICPROP% /VALUE ^|^| ^
2^> nul wmic DataFile WHERE Name^="!FILE!" GET %WMICPROP% /VALUE
') do for /F %%I in ("%%J") do (
endlocal
set "FAGE=%%I"
setlocal EnableDelayedExpansion
if !FAGE! GTR !LASTFAGE! (
endlocal
set "LASTFILE=%%F"
set "LASTFAGE=%%I"
setlocal EnableDelayedExpansion
)
)
endlocal
)
if defined LASTFILE (
setlocal EnableDelayedExpansion
REM Do whatever you want with the file here...
ECHO Newest file: "!LASTFILE!"
endlocal
)
)
popd
endlocal
exit /B
I have a large number of text files.
I need a batch script that reads each file, and renames it to the last word of second line.
The last word of 2nd line of these text files is unique within the given set of files.
#ECHO OFF
SETLOCAL
SET "sourcedir=."
FOR /f "delims=" %%a IN ('dir /b /a-d "%sourcedir%\*.txt"') DO (
SET "found="
FOR /f "skip=1delims=" %%b IN ('type "%sourcedir%\%%a"') DO IF NOT DEFINED found (
SET "found=%%b"
SETLOCAL ENABLEDELAYEDEXPANSION
SET "found=!found:"=!"
SET "found=!found: =.!"
FOR /f %%c IN ("!found!") DO SET "found=%%~xc"
ECHO REN "%sourcedir%\%%a" "!found:~1!.txt"
ENDLOCAL
)
)
GOTO :EOF
The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO REN to REN to actually rename the files.
I searched extensively and found what I believe to be a solution to my problem, which is merging CSV files without duplicating headers each time. It looks like it works, except it's only copying the first file in the folder into the destination file. I think it's unable to open the files because they have a space in the name. I've been advised I probably just need to put quotes somewhere, but I'm not sure where they would go. Thanks in advance.
#ECHO OFF
SET first=y
SET newfile=new.csv
for %%F in (*.csv) do IF NOT %%F==%newfile% (
if defined first (
COPY /y "%%F" %newfile% >nul
set "first="
) else (
FOR /f "skip=1delims=" %%i IN (%%F) DO >> %newfile% ECHO %%i
)
)
#echo off
setlocal enableextensions disabledelayedexpansion
rem configure paths
set "source=*.csv"
set "target=newfile.csv"
rem remove output file if needed
if exist "%target%" del "%target%" >nul 2>nul
rem search for header row
set "headerRow="
for %%f in ("%source%") do (
<"%%~ff" ( for /l %%a in (1 1 10) do if not defined headerRow set /p "headerRow=" )
if defined headerRow goto haveHeader
)
:haveHeader
if not defined headerRow (
echo ERROR: impossible to get header row.
goto endProcess
)
rem output header to header file to use as filter.
rem header is cut to avoid findstr limitations on search strings
set "headerFile=%temp%\%~nx0_headerFile.tmp"
setlocal enableextensions enabledelayedexpansion
> "%headerFile%" echo(!headerRow:~0,125!
endlocal
rem search for input files with matching headers to join to final file
for /f "tokens=*" %%f in ('findstr /m /b /l /g:"%headerFile%" "%source%"') do (
if not exist "%target%" (
rem first file is directly copied
copy "%%~f" "%target%" /y > nul 2>nul
) else (
rem next files are filtered to exclude the header row
findstr /v /b /l /g:"%headerFile%" "%%~f" >> "%target%"
)
echo ... [%%~ff] joined to %target%
)
rem remove the temporary header file
del "%headerFile%" >nul 2>nul
:endProcess
endlocal
Here's another option.
#echo off
set "newfile=new.txt"
del "%newfile%" 2>nul
for %%a in (*.csv) do (
if not exist "%newfile%" (type "%%a" > "%newfile%") else (more +1 "%%a" >> "%newfile%")
)
ren "%newfile%" "new.csv"
#echo off &setlocal disableDelayedExpansion
set "NewFile=new.csv"
>"%NewFile%" cd .
for /f "tokens=1*delims=:" %%a in ('dir /b /a-d /od *.csv ^|findstr /nvx "%NewFile%"') do (
if %%a equ 1 (
copy /b "%%~b" "%NewFile%" >nul
) else (
for /f "skip=1delims=" %%c in ('type "%%~b"') do >>"%NewFile%" echo(%%c
)
)
sed for Windows
I think the line near the end starting "FOR /f" is mixed up and it should be:
#ECHO OFF
SET first=y
SET newfile=new.csv
for %%F in (*.csv) do IF NOT %%F==%newfile% (
if "%first%"=="y" (
COPY /y "%%F" %newfile% >nul
set "first="
) else (
FOR /f "skip=1delims=" %%i IN ("%%F") DO ECHO %%i >> %newfile%
)
)
#ECHO OFF
SET first=y
SET "newfile=new.txt"
del new.csv 2>nul >nul
for %%F in (*.csv) do (
if defined first (
COPY /y "%%F" %newfile% >nul
set "first="
) else (
FOR /f "usebackqskip=1delims=" %%i IN ("%%F") DO >> %newfile% ECHO %%i
)
)
ren %newfile% new.csv
The set "var=value" syntax ensures that any trailing spaces on the batch line are not included in the value assigned to var.
First step is to delete the new.csv file - the 2>nul >nul redirects messages and error messages from del so that the command is totally silent - whether the file exists or not.
Next, you don't need to check whether the new.csv is selected as %%F because it's just been deleed if it did exist, and the output is now to new.txt (filename not critical - actually, I'd be tempted to call it new.vsc. The critical thing is that it isn't .csv so for doesn't need to check it)
Other than the first file (a copy is faster than reading and echoing), the name of the file (in %%F) being read into %%i, since it needs to be "quoted" (to tell CMD that the spaces are not separators) you need to add the usebackq to the for/f controls.
Finally, rename your file to the desired new name.
This should fix the problem.