'How can I use a file in a command and redirect output to the same file without truncating it (Windows)?
Over 10 years ago, Mike asked the question "How can I use a file in a command and redirect output to the same file without truncating it?" for bash. I would like to ask the same question for the Windows command processor.
The requirement is doing this without creating any temporary files. Thus, AFAIK, answers involving piping will not be suitable.
This is my current code, but the output will always be 0 bytes, likely because the command processor creates the output redirection before reading the source file:
findstr.exe /v /c:"test string" file_name >file_name
Solution 1:[1]
Unlike *nix commands, there are no one line solutions on Windows for something like this.
a Possible solution, which will also cater for blank lines:
@echo off
set "file=file_name"
for /f "delims=" %%i in ('type "%file%" ^| findstr.exe /v /c:"test string" ^| find /n /v "^" ^& break ^> "%file%" ') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:*]=!"
>>"%file%" echo(!line!
endlocal
)
You have to note that any string that contains the substring test string will also be excluded.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gerhard |
