[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


How to replace one line in a file with DOS shell

Posted on 2011-05-09
Medium Priority
Last Modified: 2012-05-11
Have a formatted text file such as blank lines and tabs and spaces. Would like to replace one line with the one from command line. Some lines are over 120 characters.  I tried to loop the file, but the output lost the format. Gurus, please advise. For example,
Start here.  
This is a test.                                                                          The test is good.
I would like to recommand it to the other people.
"Seeing is believing" ....
The end.

Want to change "Seeing is believing ".... to "Seeing is still not believing" ....

How to deal with it?
Question by:jl66
  • 2
  • 2
  • 2
  • +5
LVL 97

Assisted Solution

by:Lee W, MVP
Lee W, MVP earned 240 total points
ID: 35723752
Can you explain how you tried to loop through?

The way I would do this is:

for /f "tokens=*" in %%a (filename.txt) do (
if "%%a"=="Seeing is believing " (
   echo "Seeing is still not believing">>newfilename.txt
) else (
   echo %%a>>newfilename.txt
ren filename.txt filename.txt.backup
ren newfilename.txt filename.txt

Open in new window


Expert Comment

ID: 35723772
much better to do it with VBS, or perl, grep, sed, etc.

LVL 11

Assisted Solution

brutaldev earned 160 total points
ID: 35723789
Nothing is built into the basic command line tools to do this. There are some great command-line tools to easily do this though such as F.A.R.T. Everything I could explain to you can be found here: http://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-enviro
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

LVL 30

Expert Comment

by:Randy Downs
ID: 35723812
try this - http://www.dostips.com/DtTipsStringManipulation.php

Replace - Replace a substring using string substitution
Description: To replace a substring with another string use the string substitution feature. The example shown here replaces all occurrences "teh" misspellings with "the" in the string variable str.
 set str=teh cat in teh hat
set str=%str:teh=the%

LVL 25

Assisted Solution

by:Ron Malmstead
Ron Malmstead earned 240 total points
ID: 35723826
findstr . "C:\inputfile.txt" | C:\replacecmd.exe -o "Seeing is believing" -n "Seeing is still not believing" > outputfile.txt
LVL 30

Accepted Solution

Randy Downs earned 800 total points
ID: 35723876
This is probably better than my 1st link


@echo off
REM -- Prepare the Command Processor --

::BatchSubstitude - parses a File line by line and replaces a substring"
::syntax: BatchSubstitude.bat OldStr NewStr File
::          OldStr [in] - string to be replaced
::          NewStr [in] - string to replace with
::          File   [in] - file to be parsed
:$changed 20100115
:$source http://www.dostips.com
if "%~1"=="" findstr "^::" "%~f0"&GOTO:EOF
for /f "tokens=1,* delims=]" %%A in ('"type %3|find /n /v """') do (
    set "line=%%B"
    if defined line (
        call set "line=echo.%%line:%~1=%~2%%"
        for /f "delims=" %%X in ('"echo."%%line%%""') do %%~X
    ) ELSE echo.
LVL 11

Expert Comment

by:Pieter Jordaan
ID: 35723889

funny URL.

You gets lots of re-compiled Linux tools for Windows.
They don't work as well as on Linux, but can get the job done.

cygwin is also a nice tool if you want file scripting on Windows.

The best way to do these things, is to create a Linux file server with samba.
You can mass-rename files, recursive find and replace, search all files for a word and lots, lots more.

It is also a good way to find these tools. Just google for the Linux tool that you need, then look for the windows binary using ' for windows' in your search.

LVL 59

Assisted Solution

by:Bill Prew
Bill Prew earned 560 total points
ID: 35724110
Can you provide a real sample input file as an attachment to a post here?

Also, here is a list of free and/or pay utilities for this type of thing that I have accumulated.


If you have tabs and blank lines in the file then a batch (BAT) solution will get a bit complicated.  VBS would be a better scripting tool for this, as in:

' Define needed constants
Const ForReading = 1
Const ForWriting = 2
Const TriStateUseDefault = -2

' Get input file name from command line parm, if 2 parms entered
' use second as new output file, else rewrite to input file
If (WScript.Arguments.Count > 0) Then
  sInfile = WScript.Arguments(0)
  WScript.Echo "No filename specified."
End If
If (WScript.Arguments.Count > 1) Then
  sOutfile = WScript.Arguments(1)
  sOutfile = sInfile
End If

' Create file system object
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Read entire input file into a variable and close it
Set oInfile = oFSO.OpenTextFile(sInfile, ForReading, False, TriStateUseDefault)
sData = oInfile.ReadAll
Set oInfile = Nothing

' Replace commas (,) with pipes (|)
sData = Replace(sData, "Seeing is believing", "Seeing is still not believing")

' Write file with any changes made
Set oOutfile = oFSO.OpenTextFile(sOutfile, ForWriting, True)
Set oOutfile = Nothing

' Cleanup and end
Set oFSO = Nothing

Open in new window


Author Comment

ID: 35742234
Thank all of you very much for the codes and tips. Since this one has to be written in BAT, i have to use it for specific this task. Everyone shed a great deal of light on it from different angle. I really appreciate it.
I select Number-1's 2nd input, and revised it a bit and use it for my purpose. As mentioned by Bill, BAT is hard to manage tabs, spaces, etc. However it is resolved with the trick :
type %3|find /n /v ""
The drawback is that the rest is hard to modify.
Everyone deserves a 500 points alone... Thanks a lot.

Author Closing Comment

ID: 35742292
Thanks a kot to everyone.
LVL 59

Expert Comment

by:Bill Prew
ID: 35753374
Welcome, thank you.


Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It is only natural that we all want our PCs to be in good working order, improved system performance, so that is exactly how programs are advertised to entice. They say things like:            •      PC crashes? Get registry cleaner to repair it!    …
Being a system administrator some time we require to do things remotely, one of them is installing software. Here I am going to tell you how to install software through wmic (Windows management instrument console). I am not at all saying that this i…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question