Batch File Check for String in Other File
I have a batch file that writes a line with an ip and a name for the ip in the etc/hosts file. Is there a way to check if this line already exists? Or alternatively just see if a word exists in the file?
edit:
want something like if string exists move on but if not echo
initial code
findstr "mystring" "C:WindowsSystem32driversetchosts" >nul 2>&1
if errorlevel 1 echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS
Solved: with suggested enhancements
findstr /V "^#" "C:WindowsSystem32driversetchosts" | findstr /ILC:"mystring" >nul 2>&1 ||^
(echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS)
- can ignore commented out lines
- can search for case-insensitive string
- will write a string if string not found
windows batch-file
add a comment |
I have a batch file that writes a line with an ip and a name for the ip in the etc/hosts file. Is there a way to check if this line already exists? Or alternatively just see if a word exists in the file?
edit:
want something like if string exists move on but if not echo
initial code
findstr "mystring" "C:WindowsSystem32driversetchosts" >nul 2>&1
if errorlevel 1 echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS
Solved: with suggested enhancements
findstr /V "^#" "C:WindowsSystem32driversetchosts" | findstr /ILC:"mystring" >nul 2>&1 ||^
(echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS)
- can ignore commented out lines
- can search for case-insensitive string
- will write a string if string not found
windows batch-file
4
usefindstr
and conditional execution on success/fail&&/||
– LotPings
Dec 27 '18 at 18:43
2
What happens if the line already exists but is preceded by a comment character?
– Compo
Dec 27 '18 at 20:10
Im curious to @Compo 's question as well. If there is a way to prevent findstr from searching commented out lines.
– FamousAv8er
Dec 27 '18 at 20:15
1
Exclude comment lines first handfindstr /V "^#" C:WindowsSystem32driversetchosts | findstr /ILC:"mystring" >nul 2>&1 || (echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS)
– LotPings
Dec 27 '18 at 20:51
Cant tag you here but thank you for your help.
– FamousAv8er
Dec 27 '18 at 21:33
add a comment |
I have a batch file that writes a line with an ip and a name for the ip in the etc/hosts file. Is there a way to check if this line already exists? Or alternatively just see if a word exists in the file?
edit:
want something like if string exists move on but if not echo
initial code
findstr "mystring" "C:WindowsSystem32driversetchosts" >nul 2>&1
if errorlevel 1 echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS
Solved: with suggested enhancements
findstr /V "^#" "C:WindowsSystem32driversetchosts" | findstr /ILC:"mystring" >nul 2>&1 ||^
(echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS)
- can ignore commented out lines
- can search for case-insensitive string
- will write a string if string not found
windows batch-file
I have a batch file that writes a line with an ip and a name for the ip in the etc/hosts file. Is there a way to check if this line already exists? Or alternatively just see if a word exists in the file?
edit:
want something like if string exists move on but if not echo
initial code
findstr "mystring" "C:WindowsSystem32driversetchosts" >nul 2>&1
if errorlevel 1 echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS
Solved: with suggested enhancements
findstr /V "^#" "C:WindowsSystem32driversetchosts" | findstr /ILC:"mystring" >nul 2>&1 ||^
(echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS)
- can ignore commented out lines
- can search for case-insensitive string
- will write a string if string not found
windows batch-file
windows batch-file
edited Dec 29 '18 at 16:34
Cœur
17.4k9103145
17.4k9103145
asked Dec 27 '18 at 18:20
FamousAv8er
215
215
4
usefindstr
and conditional execution on success/fail&&/||
– LotPings
Dec 27 '18 at 18:43
2
What happens if the line already exists but is preceded by a comment character?
– Compo
Dec 27 '18 at 20:10
Im curious to @Compo 's question as well. If there is a way to prevent findstr from searching commented out lines.
– FamousAv8er
Dec 27 '18 at 20:15
1
Exclude comment lines first handfindstr /V "^#" C:WindowsSystem32driversetchosts | findstr /ILC:"mystring" >nul 2>&1 || (echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS)
– LotPings
Dec 27 '18 at 20:51
Cant tag you here but thank you for your help.
– FamousAv8er
Dec 27 '18 at 21:33
add a comment |
4
usefindstr
and conditional execution on success/fail&&/||
– LotPings
Dec 27 '18 at 18:43
2
What happens if the line already exists but is preceded by a comment character?
– Compo
Dec 27 '18 at 20:10
Im curious to @Compo 's question as well. If there is a way to prevent findstr from searching commented out lines.
– FamousAv8er
Dec 27 '18 at 20:15
1
Exclude comment lines first handfindstr /V "^#" C:WindowsSystem32driversetchosts | findstr /ILC:"mystring" >nul 2>&1 || (echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS)
– LotPings
Dec 27 '18 at 20:51
Cant tag you here but thank you for your help.
– FamousAv8er
Dec 27 '18 at 21:33
4
4
use
findstr
and conditional execution on success/fail &&/||
– LotPings
Dec 27 '18 at 18:43
use
findstr
and conditional execution on success/fail &&/||
– LotPings
Dec 27 '18 at 18:43
2
2
What happens if the line already exists but is preceded by a comment character?
– Compo
Dec 27 '18 at 20:10
What happens if the line already exists but is preceded by a comment character?
– Compo
Dec 27 '18 at 20:10
Im curious to @Compo 's question as well. If there is a way to prevent findstr from searching commented out lines.
– FamousAv8er
Dec 27 '18 at 20:15
Im curious to @Compo 's question as well. If there is a way to prevent findstr from searching commented out lines.
– FamousAv8er
Dec 27 '18 at 20:15
1
1
Exclude comment lines first hand
findstr /V "^#" C:WindowsSystem32driversetchosts | findstr /ILC:"mystring" >nul 2>&1 || (echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS)
– LotPings
Dec 27 '18 at 20:51
Exclude comment lines first hand
findstr /V "^#" C:WindowsSystem32driversetchosts | findstr /ILC:"mystring" >nul 2>&1 || (echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS)
– LotPings
Dec 27 '18 at 20:51
Cant tag you here but thank you for your help.
– FamousAv8er
Dec 27 '18 at 21:33
Cant tag you here but thank you for your help.
– FamousAv8er
Dec 27 '18 at 21:33
add a comment |
2 Answers
2
active
oldest
votes
If I understand the question, may be this can handle this:
(
(
findstr /ilc:"mystring" "C:WindowsSystem32driversetchosts"
) 2>nul >nul && (
echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS
) || (
goto :next
)
)
add a comment |
I suggest following batch file code for this task:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "HostsFile=%SystemRoot%System32driversetchosts"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%Sysnativecmd.exe set "HostsFile=%SystemRoot%Sysnativedriversetchosts"
if not exist %HostsFile% goto AppendData
%SystemRoot%System32findstr.exe /I /L /C:"mystring" %HostsFile% >nul
if not errorlevel 1 goto EndBatch
%SystemRoot%System32findstr.exe /R /V "$" %HostsFile% >nul
if not errorlevel 1 echo/>>%HostsFile%
:AppendData
>>%HostsFile% echo 111.222.33.44 mystring
:EndBatch
endlocal
The third line defines the environment variable HostsFile
with standard file path which is right on batch file being executed on 32-bit Windows by 32-bit cmd.exe
or on 64-bit Windows by 64-bit cmd.exe
in directory %SystemRoot%System32
.
The fourth line takes into account the Windows File System Redirector according to WOW64 Implementation Details. The batch file is executed on 64-bit Windows if there is defined an environment variable with name ProgramFiles(x86)
with a non-empty value. But the batch file is executed by 32-bit cmd.exe
in directory %SystemRoot%SysWOW64
if there is %SystemRoot%Sysnativecmd.exe
. The redirector Sysnative
does not exist for x64 applications. In this case the file hosts
must be referenced from within 32-bit environment on 64-bit Windows with using the Sysnative
redirector in file path.
Next is checked if the file hosts
exists at all. If the file does not exist, the data line to append can be directly written to the file without any further checks whereby the file hosts
is created in this case.
Otherwise the command FINDSTR is used to search case-insensitive with a literally interpreted search string for mystring
with redirecting the perhaps found line(s) to device NUL. FINDSTR exits with value 0
if there is at least one positive match and with value 1
if the searched string could not be found on any line.
if not errorlevel 1
means IF exit code is NOT GREATER OR EQUAL 1, or in other words LOWER THAN 1, or in this case EQUAL 0 because of FINDSTR never exits with a negative value as nearly all applications and commands. So if this condition is true, the file hosts
contains at least once the searched string and nothing to change on file.
Otherwise FINDSTR is used once more to search this time with a regular expression for end of line and to output all lines not having a line ending because of option /V
. So if last line in file hosts
has no line ending, FINDSTR exits with value 0
because of having output one line with no line ending whereby this output is redirected to device NUL.
A line ending is appended to file hosts
if FINDSTR exited with value 0
because of file hosts
ends with no line ending before appending next the data line to add to this file.
The code above does not work if the batch file is not executed with elevated permissions of a local administrator or the file hosts
has read-only attribute set or is otherwise protected against modification by a script.
BTW: An octet of an IPv4 address cannot be greater than 255. So 111.222.333.444
is a terrible example for an IPv4 address added to file hosts
because of being an invalid IPv4 address.
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.
echo /?
endlocal /?
findstr /?
goto /?
if /?
set /?
setlocal /?
See also DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53949233%2fbatch-file-check-for-string-in-other-file%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
If I understand the question, may be this can handle this:
(
(
findstr /ilc:"mystring" "C:WindowsSystem32driversetchosts"
) 2>nul >nul && (
echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS
) || (
goto :next
)
)
add a comment |
If I understand the question, may be this can handle this:
(
(
findstr /ilc:"mystring" "C:WindowsSystem32driversetchosts"
) 2>nul >nul && (
echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS
) || (
goto :next
)
)
add a comment |
If I understand the question, may be this can handle this:
(
(
findstr /ilc:"mystring" "C:WindowsSystem32driversetchosts"
) 2>nul >nul && (
echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS
) || (
goto :next
)
)
If I understand the question, may be this can handle this:
(
(
findstr /ilc:"mystring" "C:WindowsSystem32driversetchosts"
) 2>nul >nul && (
echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS
) || (
goto :next
)
)
answered Dec 28 '18 at 11:41
kaputtz
194111
194111
add a comment |
add a comment |
I suggest following batch file code for this task:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "HostsFile=%SystemRoot%System32driversetchosts"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%Sysnativecmd.exe set "HostsFile=%SystemRoot%Sysnativedriversetchosts"
if not exist %HostsFile% goto AppendData
%SystemRoot%System32findstr.exe /I /L /C:"mystring" %HostsFile% >nul
if not errorlevel 1 goto EndBatch
%SystemRoot%System32findstr.exe /R /V "$" %HostsFile% >nul
if not errorlevel 1 echo/>>%HostsFile%
:AppendData
>>%HostsFile% echo 111.222.33.44 mystring
:EndBatch
endlocal
The third line defines the environment variable HostsFile
with standard file path which is right on batch file being executed on 32-bit Windows by 32-bit cmd.exe
or on 64-bit Windows by 64-bit cmd.exe
in directory %SystemRoot%System32
.
The fourth line takes into account the Windows File System Redirector according to WOW64 Implementation Details. The batch file is executed on 64-bit Windows if there is defined an environment variable with name ProgramFiles(x86)
with a non-empty value. But the batch file is executed by 32-bit cmd.exe
in directory %SystemRoot%SysWOW64
if there is %SystemRoot%Sysnativecmd.exe
. The redirector Sysnative
does not exist for x64 applications. In this case the file hosts
must be referenced from within 32-bit environment on 64-bit Windows with using the Sysnative
redirector in file path.
Next is checked if the file hosts
exists at all. If the file does not exist, the data line to append can be directly written to the file without any further checks whereby the file hosts
is created in this case.
Otherwise the command FINDSTR is used to search case-insensitive with a literally interpreted search string for mystring
with redirecting the perhaps found line(s) to device NUL. FINDSTR exits with value 0
if there is at least one positive match and with value 1
if the searched string could not be found on any line.
if not errorlevel 1
means IF exit code is NOT GREATER OR EQUAL 1, or in other words LOWER THAN 1, or in this case EQUAL 0 because of FINDSTR never exits with a negative value as nearly all applications and commands. So if this condition is true, the file hosts
contains at least once the searched string and nothing to change on file.
Otherwise FINDSTR is used once more to search this time with a regular expression for end of line and to output all lines not having a line ending because of option /V
. So if last line in file hosts
has no line ending, FINDSTR exits with value 0
because of having output one line with no line ending whereby this output is redirected to device NUL.
A line ending is appended to file hosts
if FINDSTR exited with value 0
because of file hosts
ends with no line ending before appending next the data line to add to this file.
The code above does not work if the batch file is not executed with elevated permissions of a local administrator or the file hosts
has read-only attribute set or is otherwise protected against modification by a script.
BTW: An octet of an IPv4 address cannot be greater than 255. So 111.222.333.444
is a terrible example for an IPv4 address added to file hosts
because of being an invalid IPv4 address.
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.
echo /?
endlocal /?
findstr /?
goto /?
if /?
set /?
setlocal /?
See also DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
add a comment |
I suggest following batch file code for this task:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "HostsFile=%SystemRoot%System32driversetchosts"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%Sysnativecmd.exe set "HostsFile=%SystemRoot%Sysnativedriversetchosts"
if not exist %HostsFile% goto AppendData
%SystemRoot%System32findstr.exe /I /L /C:"mystring" %HostsFile% >nul
if not errorlevel 1 goto EndBatch
%SystemRoot%System32findstr.exe /R /V "$" %HostsFile% >nul
if not errorlevel 1 echo/>>%HostsFile%
:AppendData
>>%HostsFile% echo 111.222.33.44 mystring
:EndBatch
endlocal
The third line defines the environment variable HostsFile
with standard file path which is right on batch file being executed on 32-bit Windows by 32-bit cmd.exe
or on 64-bit Windows by 64-bit cmd.exe
in directory %SystemRoot%System32
.
The fourth line takes into account the Windows File System Redirector according to WOW64 Implementation Details. The batch file is executed on 64-bit Windows if there is defined an environment variable with name ProgramFiles(x86)
with a non-empty value. But the batch file is executed by 32-bit cmd.exe
in directory %SystemRoot%SysWOW64
if there is %SystemRoot%Sysnativecmd.exe
. The redirector Sysnative
does not exist for x64 applications. In this case the file hosts
must be referenced from within 32-bit environment on 64-bit Windows with using the Sysnative
redirector in file path.
Next is checked if the file hosts
exists at all. If the file does not exist, the data line to append can be directly written to the file without any further checks whereby the file hosts
is created in this case.
Otherwise the command FINDSTR is used to search case-insensitive with a literally interpreted search string for mystring
with redirecting the perhaps found line(s) to device NUL. FINDSTR exits with value 0
if there is at least one positive match and with value 1
if the searched string could not be found on any line.
if not errorlevel 1
means IF exit code is NOT GREATER OR EQUAL 1, or in other words LOWER THAN 1, or in this case EQUAL 0 because of FINDSTR never exits with a negative value as nearly all applications and commands. So if this condition is true, the file hosts
contains at least once the searched string and nothing to change on file.
Otherwise FINDSTR is used once more to search this time with a regular expression for end of line and to output all lines not having a line ending because of option /V
. So if last line in file hosts
has no line ending, FINDSTR exits with value 0
because of having output one line with no line ending whereby this output is redirected to device NUL.
A line ending is appended to file hosts
if FINDSTR exited with value 0
because of file hosts
ends with no line ending before appending next the data line to add to this file.
The code above does not work if the batch file is not executed with elevated permissions of a local administrator or the file hosts
has read-only attribute set or is otherwise protected against modification by a script.
BTW: An octet of an IPv4 address cannot be greater than 255. So 111.222.333.444
is a terrible example for an IPv4 address added to file hosts
because of being an invalid IPv4 address.
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.
echo /?
endlocal /?
findstr /?
goto /?
if /?
set /?
setlocal /?
See also DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
add a comment |
I suggest following batch file code for this task:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "HostsFile=%SystemRoot%System32driversetchosts"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%Sysnativecmd.exe set "HostsFile=%SystemRoot%Sysnativedriversetchosts"
if not exist %HostsFile% goto AppendData
%SystemRoot%System32findstr.exe /I /L /C:"mystring" %HostsFile% >nul
if not errorlevel 1 goto EndBatch
%SystemRoot%System32findstr.exe /R /V "$" %HostsFile% >nul
if not errorlevel 1 echo/>>%HostsFile%
:AppendData
>>%HostsFile% echo 111.222.33.44 mystring
:EndBatch
endlocal
The third line defines the environment variable HostsFile
with standard file path which is right on batch file being executed on 32-bit Windows by 32-bit cmd.exe
or on 64-bit Windows by 64-bit cmd.exe
in directory %SystemRoot%System32
.
The fourth line takes into account the Windows File System Redirector according to WOW64 Implementation Details. The batch file is executed on 64-bit Windows if there is defined an environment variable with name ProgramFiles(x86)
with a non-empty value. But the batch file is executed by 32-bit cmd.exe
in directory %SystemRoot%SysWOW64
if there is %SystemRoot%Sysnativecmd.exe
. The redirector Sysnative
does not exist for x64 applications. In this case the file hosts
must be referenced from within 32-bit environment on 64-bit Windows with using the Sysnative
redirector in file path.
Next is checked if the file hosts
exists at all. If the file does not exist, the data line to append can be directly written to the file without any further checks whereby the file hosts
is created in this case.
Otherwise the command FINDSTR is used to search case-insensitive with a literally interpreted search string for mystring
with redirecting the perhaps found line(s) to device NUL. FINDSTR exits with value 0
if there is at least one positive match and with value 1
if the searched string could not be found on any line.
if not errorlevel 1
means IF exit code is NOT GREATER OR EQUAL 1, or in other words LOWER THAN 1, or in this case EQUAL 0 because of FINDSTR never exits with a negative value as nearly all applications and commands. So if this condition is true, the file hosts
contains at least once the searched string and nothing to change on file.
Otherwise FINDSTR is used once more to search this time with a regular expression for end of line and to output all lines not having a line ending because of option /V
. So if last line in file hosts
has no line ending, FINDSTR exits with value 0
because of having output one line with no line ending whereby this output is redirected to device NUL.
A line ending is appended to file hosts
if FINDSTR exited with value 0
because of file hosts
ends with no line ending before appending next the data line to add to this file.
The code above does not work if the batch file is not executed with elevated permissions of a local administrator or the file hosts
has read-only attribute set or is otherwise protected against modification by a script.
BTW: An octet of an IPv4 address cannot be greater than 255. So 111.222.333.444
is a terrible example for an IPv4 address added to file hosts
because of being an invalid IPv4 address.
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.
echo /?
endlocal /?
findstr /?
goto /?
if /?
set /?
setlocal /?
See also DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
I suggest following batch file code for this task:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "HostsFile=%SystemRoot%System32driversetchosts"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%Sysnativecmd.exe set "HostsFile=%SystemRoot%Sysnativedriversetchosts"
if not exist %HostsFile% goto AppendData
%SystemRoot%System32findstr.exe /I /L /C:"mystring" %HostsFile% >nul
if not errorlevel 1 goto EndBatch
%SystemRoot%System32findstr.exe /R /V "$" %HostsFile% >nul
if not errorlevel 1 echo/>>%HostsFile%
:AppendData
>>%HostsFile% echo 111.222.33.44 mystring
:EndBatch
endlocal
The third line defines the environment variable HostsFile
with standard file path which is right on batch file being executed on 32-bit Windows by 32-bit cmd.exe
or on 64-bit Windows by 64-bit cmd.exe
in directory %SystemRoot%System32
.
The fourth line takes into account the Windows File System Redirector according to WOW64 Implementation Details. The batch file is executed on 64-bit Windows if there is defined an environment variable with name ProgramFiles(x86)
with a non-empty value. But the batch file is executed by 32-bit cmd.exe
in directory %SystemRoot%SysWOW64
if there is %SystemRoot%Sysnativecmd.exe
. The redirector Sysnative
does not exist for x64 applications. In this case the file hosts
must be referenced from within 32-bit environment on 64-bit Windows with using the Sysnative
redirector in file path.
Next is checked if the file hosts
exists at all. If the file does not exist, the data line to append can be directly written to the file without any further checks whereby the file hosts
is created in this case.
Otherwise the command FINDSTR is used to search case-insensitive with a literally interpreted search string for mystring
with redirecting the perhaps found line(s) to device NUL. FINDSTR exits with value 0
if there is at least one positive match and with value 1
if the searched string could not be found on any line.
if not errorlevel 1
means IF exit code is NOT GREATER OR EQUAL 1, or in other words LOWER THAN 1, or in this case EQUAL 0 because of FINDSTR never exits with a negative value as nearly all applications and commands. So if this condition is true, the file hosts
contains at least once the searched string and nothing to change on file.
Otherwise FINDSTR is used once more to search this time with a regular expression for end of line and to output all lines not having a line ending because of option /V
. So if last line in file hosts
has no line ending, FINDSTR exits with value 0
because of having output one line with no line ending whereby this output is redirected to device NUL.
A line ending is appended to file hosts
if FINDSTR exited with value 0
because of file hosts
ends with no line ending before appending next the data line to add to this file.
The code above does not work if the batch file is not executed with elevated permissions of a local administrator or the file hosts
has read-only attribute set or is otherwise protected against modification by a script.
BTW: An octet of an IPv4 address cannot be greater than 255. So 111.222.333.444
is a terrible example for an IPv4 address added to file hosts
because of being an invalid IPv4 address.
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.
echo /?
endlocal /?
findstr /?
goto /?
if /?
set /?
setlocal /?
See also DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
answered Dec 29 '18 at 17:38
Mofi
27.6k83777
27.6k83777
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53949233%2fbatch-file-check-for-string-in-other-file%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
use
findstr
and conditional execution on success/fail&&/||
– LotPings
Dec 27 '18 at 18:43
2
What happens if the line already exists but is preceded by a comment character?
– Compo
Dec 27 '18 at 20:10
Im curious to @Compo 's question as well. If there is a way to prevent findstr from searching commented out lines.
– FamousAv8er
Dec 27 '18 at 20:15
1
Exclude comment lines first hand
findstr /V "^#" C:WindowsSystem32driversetchosts | findstr /ILC:"mystring" >nul 2>&1 || (echo 111.222.333.444 mystring>>%systemroot%SYSTEM32DRIVERSETCHOSTS)
– LotPings
Dec 27 '18 at 20:51
Cant tag you here but thank you for your help.
– FamousAv8er
Dec 27 '18 at 21:33