views:

200

answers:

4

I want a batch file which: removes a certain line [line number by %lnum%] in a txt file.

+3  A: 

That sounds like a job for sed. On windows, you'd have to install a windows port and then call sed from within your batch file.

sed '<linenumber>d' filename > newfilename

To delete the 4th line:

sed '4d' filename > newfilename
Matt Bridges
hmmm... when i installed sed and restarted my computer, it wasn't found by CMD. i have Win7.
YourComputerHelpZ
oh, i know how it works now.
YourComputerHelpZ
A: 

If you are in windows and you want to do it in a batch file, you could do the following by brute force:

@echo off
setlocal ENABLEDELAYEDEXPANSION
SET lineNum=
SET filename=%1
SET targetLine=%2
SET targetFile=%filename%.tmp
DEL %targetFile%
FOR /F "    tokens=1 delims=" %%i in (%filename%) do (
  SET /a lineNum += 1 
  if NOT !lineNum! == !targetLine! ECHO %%i >> !targetFile!
)
REN %filename% %filename%.orig
REN %targetFile% %filename%

You pass into the batch the name of your target file and the line number you want removed. It creates a temporary file, pipes the 'good' lines from your original into the temp and then finishes up by renaming the files so that you keep your original and have the modified file in place.

akf
A: 

don't have to use any external command. you can use vbscript

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
num = objArgs(0)
strFile = objArgs(1)
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfLine
    linenum = objFile.Line 
    If linenum = Int(num) Then
     objFile.SkipLine
    End If 
    strLine = objFile.ReadLine
    WScript.Echo strLine
Loop

how to use:

C:\test>cscript /nologo removeline.vbs 4 file.txt > newfile.txt
ghostdog74
A: 

Pure cmd?:

delline.cmd number filename

@echo off
setlocal ENABLEDELAYEDEXPANSION
set line=%~1
set file=%~nx2
set dSource=%~dp2
set i=0
for /F "delims=" %%l in (%dSource%%file%) do (
    set /a i+=1
    if not !i! EQU %line% call :BuildFile "%%l"
)
del /f "%dSource%%file%" >nul
for %%l in (%_file%) do echo %%~l>>"%dSource%%file%"
endlocal& exit /b 0

:BuildFile
    set _file=%_file% %1
    exit /b 0

___Notes_____
1: No checks for parameters. First need be a number, the second a file or path+file.
2: As with other answers, no temporary file either.
3: Using setlocal would allow you to integrate this code easy within a script by naming it :delline and using it like: call :delline number file

WARNING: Any blank line from the source file would be skipped/lost in the reading process (by the for..loop). A file with, says 10 lines from which 4 are blanks, would be read as 6 lines to be processed. The line number given would be applied (thus, deleted) from the 6 data lines, and not the starting 10.

Edit
Went a bit too fast, did not see akf's answer which looks real close to mine.

Jay