Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am wondering if I can tell the computer to do a command on a text file with a batch file, however I would like to specify which line to modify.

I do not have any code for this yet and I would be grateful if you could give a detailed explanation.

When and if I get this command I am planing to use it to delete or write on that exact line and not overwrite another.

share|improve this question
batch files on their own are pretty horrible for text operations. Are you averse to using stuff like sed or awk, or powershell? – Journeyman Geek Jul 23 '12 at 2:04
i dont know what 'sed,awk or powershell' is but if you are refering to programing languages then no. – Zacyboy11 Jul 23 '12 at 2:21

Doing this through the Windows command prompt is more fun than it is practical, but it is possible. You can use for /f to go through a file one line at a time, but I know of no trivial way to keep track of the current line. The following code uses a call to a subroutine to count the lines manually. The batch file is to be called using the filename, line number to replace and the replacing string.

@echo off
set filename=%1
set targetline=%2
set message=%3
set n=0
for /F "tokens=*" %%i in (%filename%) do call :write %%i
exit /b 0

set /a n+=1
if %n%==%targetline% (echo %message%) else echo %*
exit /b 0

Sample output of replace.bat somelines.txt 3 "Hello, world!":

first line
second line
"Hello, world!"
fourth line
share|improve this answer
Cool thanx, so by using for /f i can set the line to use. – Zacyboy11 Jul 23 '12 at 23:34

Sed for Windows will allow you to perform line-oriented operations on text files:

Sed (streams editor) isn't really a true text editor or text processor. Instead, it is used to filter text, i.e., it takes text input and performs some operation (or set of operations) on it and outputs the modified text. Sed is typically used for extracting part of a file using pattern matching or substituting multiple occurances of a string within a file.

share|improve this answer
how do i use sed? – Zacyboy11 Jul 23 '12 at 2:22
That all depends on what you're doing. I recommend you find a good tutorial and a sturdy reference, since sed is one of the largest text manipulation tools in use, and having even a passing knowledge of it is useful. – Ignacio Vazquez-Abrams Jul 23 '12 at 2:23
what do you suggest i seach into google to get a good reference on this? – Zacyboy11 Jul 23 '12 at 2:25
i have never heard of it :( – Zacyboy11 Jul 23 '12 at 2:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .