user2562356
user2562356

Reputation: 11

Replace a character in a file using a batch script

I am new to batch file scripting and need to develop a script to replace a character in a file using a batch script.

I have to replace "servername/ActionService.asmx,1" with "servername/ActionService.asmx,0" in file called APP.

Please let me know if there is any solution using only commands.

Upvotes: 1

Views: 2603

Answers (6)

foxidrive
foxidrive

Reputation: 41224

Using a helper batch file called repl.bat from here: http://www.dostips.com/forum/viewtopic.php?f=3&t=3855

type app |repl "servername\/ActionService.asmx,1" "servername/ActionService.asmx,0" >appnew.txt

Upvotes: 0

Magoo
Magoo

Reputation: 79982

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
:: Way the first - suppresses emptylines
FOR /f "delims=" %%i IN (app) DO SET line=%%i&set line=!line:servername/ActionService.asmx,1=servername/ActionService.asmx,0!&ECHO(!line!
ECHO ====================
:: Way the second 
FOR /f "delims=" %%i IN ('type app^|findstr /n "$"') DO (
  SET line=%%i
  set line=!line:servername/ActionService.asmx,1=servername/ActionService.asmx,0!
  SET line=!line:*:=!
  ECHO(!line!
)
ECHO ====================
GOTO :EOF

Two ways here. You would need to redirect your choice to a new file as you cannot update in-place.

Upvotes: 1

Aacini
Aacini

Reputation: 67196

The Batch file below assume that there is precisely one line with the target string. This method is relatively fast.

@echo off
for /F "delims=:" %%a in ('findstr /N "servername/ActionService.asmx,1" theFile.txt') do set lineNum=%%a
(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" theFile.txt do (
   set "line=%%b"
   setlocal EnableDelayedExpansion
   if %%a equ %lineNum% (
      echo !line:1=0!
   ) else (
      echo(!line!
   )
   endlocal
)) > theFile.new

Upvotes: 1

Endoro
Endoro

Reputation: 37569

You can use GNUWin32 sed:

@ECHO OFF &SETLOCAL
set "string=servername/ActionService.asmx,1"
FOR /f %%a IN ('echo "%string%" ^| sed "s/[0-9]/0/"') DO set "newstring=%%~a"
ECHO %newstring%

Upvotes: 2

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20600

If you're toggling back and forth between these two states, it might be easier to create two copies of the file with different names, together with a couple of batch files (e.g. actionService1.bat and actionService2.bat) to copy the appropriate file over your APP file.

Otherwise you might consider getting Windows versions of the Unix tools sed and awk, which excel at this type of file manipulation.

Upvotes: 1

HKImpact
HKImpact

Reputation: 620

Doing a quick google search I found this http://www.dostips.com/?t=Batch.FindAndReplace

Upvotes: 0

Related Questions