dkbhadeshiya
dkbhadeshiya

Reputation: 179

String replace using Batch File Commands

Want to replace some strings in a text file "list.txt" using batch file commands.

I want to replace C:\ in the file "list.txt" with "adb install C:\" using some batch file commands in windows.

And remove the line containing ".txt" file from "list.txt"

in linux i used to do this with grep command

how to do this?

Upvotes: 0

Views: 232

Answers (3)

Steve In CO
Steve In CO

Reputation: 6174

I was looking for a quick and dirty way to do some simple search/replace with built in batch file commands but not a lot of code. This question popped up at the top and the answer from @Endoro is close to what I needed, but it has a few issues. One is a typo (should be %inFileName% not %FileName%), the other is that it outputs C:\=adb install C:\ for blank lines.

Below is modified version of his batch script that fixes both problems and uses environment variables for search and replace values. I did not need the removal of the .txt line so I removed that part. It haven't tested extensively, but it does suit my purposes. Maybe it will help somebody else too.

@ECHO OFF &SETLOCAL disableDelayedExpansion
SET "inFileName=infile.txt"
SET "outFileName=outfile.txt"
SET "SearchVal=C:\"
Set "ReplaceVal=adb install C:\"
(FOR /f "delims=" %%a IN ('FINDSTR /n "^" "%inFileName%"') DO (
    SET "PrimLine=%%a"
    SETLOCAL enableDelayedExpansion
    SET "Line=!PrimLine:*:=!"
    SET "Line=!Line:%SearchVal%=%ReplaceVal%!"
    IF "%SearchVal%=%ReplaceVal%"=="!Line!" ECHO.
    IF NOT "%SearchVal%=%ReplaceVal%"=="!Line!" ECHO(!Line!
    ENDLOCAL
))>"%outFileName%"

Upvotes: 0

Endoro
Endoro

Reputation: 37589

try this:

@ECHO OFF &SETLOCAL disableDelayedExpansion
SET "inFileName=infile.txt"
SET "outFileName=outfile.txt"
(FOR /f "delims=" %%a IN ('FINDSTR /n "^" "%FileName%"') DO (
    SET "PrimLine=%%a"
    SETLOCAL enableDelayedExpansion
    SET "Line=!PrimLine:*:=!"
    SET "Line=!Line:C:\=adb install C:\!"
    IF "!Line:txt=!"=="!Line!" ECHO(!Line!
    ENDLOCAL
))>"%outFileName%"

Upvotes: 1

cup
cup

Reputation: 8299

Try the following

for /f "usebackq delims=." %x in (`findstr C:\ list.txt`) do echo adb install %x

for /f will pick off the contents of list.txt one at a time

delims=. stops at the first . The drawback is that if there are two . in the filename, it only stops at the first one.

Upvotes: 0

Related Questions