Reputation: 13
I have a text file called Test.OPT
with the below contents:
REPORTLOG +"E:\LicenseLogs\cstd.rl"
GROUPCASEINSENSITIVE ON
GROUP TEST_USERS user1 user2
INCLUDE feature1 TEST_USERS
INCLUDE feature2 TEST_USERS
INCLUDE Solver_feature3 TEST_USERS
INCLUDE Solver_feature4 TEST_USERS
INCLUDE Solver_feature5 TEST_USERS
INCLUDE Solver_feature6 TEST_USERS
INCLUDE Solver_feature7 TEST_USERS
I want to append to end of the line containing GROUP TEST_USERS
the string User3
in above text file.
I have below a batch file which does not work as expected:
@echo off
setlocal EnableDelayedExpansion
set search=%1
set "textfile=D:\testing\Test.OPT"
set "newfile=D:\testing\TestTemp.OPT"
(for /f "delims=" %%i in (%textfile%) do (
set "line=%%i"
findStr /B /c:"GROUP TEST_USERS" %%i>nul && (
set line=%%i %search%
) || (
set "line=%%i"
)
echo(!line!
endlocal
))>"%newfile%"
I could do this easily in Java, but due to some reason I'm forced to do this with a batch script.
Upvotes: 1
Views: 44
Reputation: 49086
I suggest following code for this task:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "search=%~1"
set "textfile=D:\testing\Test.OPT"
set "newfile=D:\testing\TestTemp.OPT"
(for /F "usebackq delims=" %%i in ("%textfile%") do (
set "line=%%i"
if not "!line:GROUP TEST_USERS=!" == "!line!" (
set "UserCheck=!line! "
if "!UserCheck: %search% =!" == "!UserCheck!" set "line=!line! %search%"
)
echo(!line!
))>"%newfile%"
%SystemRoot%\System32\fc.exe /B "%textfile%" "%newfile%" >nul
if errorlevel 1 move /Y "%newfile%" "%textfile%" 2>nul
if exist "%newfile%" del "%newfile%"
endlocal
The first IF condition compares case-sensitive the line with all occurrences of GROUP TEST_USERS
substituted case-insensitive by an empty string with current line. The current line contains GROUP TEST_USERS
if the two compared strings are not equal.
On line containing GROUP TEST_USERS
the line is assigned with a trailing space to environment variable UserCheck
.
The second IF is similar to first IF to find out if the line contains already the user passed to the batch file as first argument. The user is only appended to the line on line not already containing this user.
Finally, a binary file comparison is executed for current file and new file. Only if the two files are not binary equal, the new file is moved over original file. Otherwise the new file being binary equal to original file is just deleted. So the last modification date of original file changes only if the file content is really changed, too.
Please note that this batch code does not work for text files containing empty lines, lines with one or more exclamation marks, or lines starting with a semicolon.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
echo /?
endlocal /?
fc /?
for /?
if /?
move /?
set /?
setlocal /?
Upvotes: 1