Remove lines from a file: Difference between revisions

m
→‎{{header|11l}}: new way of specifying file open mode
(Added Wren)
m (→‎{{header|11l}}: new way of specifying file open mode)
 
(17 intermediate revisions by 13 users not shown)
Line 12:
An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">:start:
V l = File(:argv[1]).read_lines()
l.del(Int(:argv[2]) - 1 .+ Int(:argv[3]))
File(:argv[1], WRITE).write(l.join("\n"))</syntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions;
use Ada.Text_IO;
 
Line 54 ⟶ 60:
"<filename>" & Temporary & " for temporary writing");
Put_Line(" requires first > 0, length >= 0");
end Remove_Lines_From_File;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># removes the specified number of lines from a file, starting at start line (numbered from 1) #
# returns TRUE if successful, FALSE otherwise #
PROC remove lines = ( STRING file name, INT start line, INT number of lines )BOOL:
Line 177 ⟶ 183:
close( t );
print( ( "----", newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 201 ⟶ 207:
----
</pre>
=={{header|Amazing Hopper}}==
Programming with macro-Hopper:
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
 
main:
.ctrlc
fd=0,fw=0
fopen(OPEN_READ,"archivo.txt")(fd)
if file error?
{"no pude abrir el archivo de lectura: "}
jsub(show error)
else
fcreate(CREATE_NORMAL,"archivoTmp.txt")(fw)
if file error?
{"no pude crear el archivo para escritura: "}
jsub(show error)
else
get arg number(2,desde), // from line
get arg number(3,hasta), // to line
 
line read=0
while( not(feof(fd)))
fread line(1000)(fd), ++line read
if(not( {line read} between(desde, hasta)))
{"\n"}cat,writeline(fw)
endif
wend
endif
endif
fclose(fw)
fclose(fd)
system("mv archivoTmp.txt archivo.txt")
exit(0)
.locals
show error:
file error, println
back
</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">removeFileLines: function [filename, start, cnt][
previous: ø
ensure -> all? @[
exists? filename
previous: read.lines filename
start < size previous
(start + cnt) < size previous
]
 
final: previous\[0..start-1] ++ previous\[start+cnt..dec size previous]
write filename join.with:"\n" final
]
 
removeFileLines "myfile.txt" 3 10</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AHKlang="ahk">RemoveLines(filename, startingLine, numOfLines){
Loop, Read, %filename%
if ( A_Index < StartingLine )
Line 213 ⟶ 275:
 
SetWorkingDir, % A_ScriptDir
RemoveLines("test.txt", 4, 3)</langsyntaxhighlight>
;Output:
with test.txt starting as
Line 232 ⟶ 294:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f REMOVE_LINES_FROM_A_FILE.AWK
# show files after lines are removed:
Line 276 ⟶ 338:
}
}
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
Line 282 ⟶ 344:
 
Verbose and with a program loop to test the procedures.
<langsyntaxhighlight lang="qbasic">
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' Remove File Lines V1.1 '
Line 590 ⟶ 652:
END FUNCTION
 
</syntaxhighlight>
</lang>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "RemLines.bas"
110 CALL REMOVELINES("fub.txt",5,3)
120 DEF REMOVELINES(NAME$,ST,N)
Line 629 ⟶ 691:
440 CLOSE #1
450 END HANDLER
460 END DEF</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h> /* for atoi() and malloc() */
#include <string.h> /* for memmove() */
Line 692 ⟶ 754:
fclose(fp);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
{{works with|C sharp|6}}
<langsyntaxhighlight lang="csharp">using System;
using System.IO;
using System.Linq;
Line 707 ⟶ 769:
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <fstream>
#include <iostream>
#include <string>
Line 767 ⟶ 829:
return ;
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Simple solution dealing with most of the lines in memory.
<langsyntaxhighlight lang="clojure">(require '[clojure.java.io :as jio]
'[clojure.string :as str])
 
Line 783 ⟶ 845:
(with-open [wrt (jio/writer (str filepath ".tmp"))]
(.write wrt (str/join "\n" new-lines)))
(.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))</langsyntaxhighlight>
 
More complex solution for big file, one line at a time.
<langsyntaxhighlight lang="clojure">(require '[clojure.java.io :as jio]
'[clojure.string :as str])
 
Line 802 ⟶ 864:
(when (pos? n)
(println "WARN: You are trying to remove lines beyond EOF"))))))
(.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath)))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun remove-lines (filename start num)
(let ((tmp-filename (concatenate 'string filename ".tmp"))
(lines-omitted 0))
Line 829 ⟶ 891:
;; Warn if line removal went past the end of the file
(when (< lines-omitted num)
(warn "End of file reached with only ~d lines removed." lines-omitted))))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.file, std.string;
 
void main() {
Line 856 ⟶ 918:
f.writeln(line);
}
}</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IoUtils}}
===Using TStringDynArray===
 
<syntaxhighlight lang="delphi">
program Remove_lines_from_a_file_using_TStringDynArray;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.IoUtils;
 
// zero started Index
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
 
var lines := TFile.ReadAllLines(FileName);
 
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
 
begin
// Remove 2th & 3td line of file
RemoveLines('input.txt', 1, 2);
end.</syntaxhighlight>
 
===Using TStringList===
{{libheader| System.SysUtils}}
{{libheader| System.Classes}}
<syntaxhighlight lang="delphi">
program Remove_lines_from_a_file_using_TStringList;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Classes;
 
// zero started Index
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
 
with TStringList.Create do
begin
LoadFromFile(FileName);
for var _ := 1 to Line_count do
begin
if Index >= Count then
Break;
Delete(Index);
end;
SaveToFile(FileName);
Free;
end;
end;
 
begin
// Remove 2th & 3td line of file
RemoveLines('input.txt', 1, 2);
end.</syntaxhighlight>
=={{header|ECL}}==
Implemented for HPCC logical files, not single physical files, since all datasets in HPCC are distributed.
<syntaxhighlight lang="ecl">
<lang ECL>
IMPORT STD;
RemoveLines(logicalfile, startline, numlines) := FUNCTIONMACRO
Line 869 ⟶ 997:
IF(RecCnt < EndLine,STD.System.Log.addWorkunitWarning('Attempted removal past end of file-removal ignored')));
ENDMACRO;
</syntaxhighlight>
</lang>
And a simple test case to run:
<syntaxhighlight lang="ecl">
<lang ECL>
MyFile := DATASET(100,TRANSFORM({UNSIGNED1 RecID},SELF.RecID := COUNTER));
RemoveLines(MyFile,3,10);
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
Line 905 ⟶ 1,033:
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)</langsyntaxhighlight>
 
{{out}}
Line 924 ⟶ 1,052:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( remove_lines ).
 
Line 954 ⟶ 1,082:
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
</syntaxhighlight>
</lang>
{{out}}
With "foobar.txt" that looks like this:
Line 982 ⟶ 1,110:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
open System.IO
 
Line 996 ⟶ 1,124:
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0</langsyntaxhighlight>
Output
<langsyntaxhighlight lang="dos">D:\Projects\Rosetta>for /l %i in (1,1,5) do @echo %i >> foo
 
D:\Projects\Rosetta>Remove_lines_from_a_file.exe foo 1 2
Line 1,007 ⟶ 1,135:
5
 
D:\Projects\Rosetta></langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,014 ⟶ 1,142:
As always, there is a problem with the length of a piece of string. The allowance here is 66666 characters. Some filesystems know the length of records, and may make the maximum record length available to enquiry, but others don't know and use instead a marker which might be CR, CRLF, LF or LFCR and even a mixture in the same file. The Fortran programme does not see this with FORMATTED input, just the content of the record, character style. Output, on a windows/DOS system, will always terminate records with CRLF. A null record would be after the first CRLF in the sequence CRLFCRLF, and so on. With UNFORMATTED, the programme must make its own decisions.
 
<syntaxhighlight lang="fortran">
<lang Fortran>
SUBROUTINE CROAK(GASP) !Something bad has happened.
CHARACTER*(*) GASP !As noted.
Line 1,066 ⟶ 1,194:
CALL FILEHACK("foobar.txt",1,2)
END
</syntaxhighlight>
</lang>
 
When run on file foobar.txt containing
Line 1,083 ⟶ 1,211:
 
Formulating error messages is tedious, in the absence of a function such as IFMT(n) to be used in <code>CALL CROAK("First record must be positive, not "//IFMT(IST))</code> A more accomplished programme would worry about running out of disc space (signalled by the taking of the END=''label'' option in a WRITE statement) and I/O errors along the way using the ERR=''label'' option, but it is difficult to devise recovery schemes for unexpected errors. Similarly, the OPEN statements are at risk of confronting a file that is available for READ, but not for WRITE. It would help in organising all this if OPEN(...) was a function, but instead one can refer to the recondite IOSTAT error codes, possibly with assistance as with
<syntaxhighlight lang="fortran">
<lang Fortran>
CHARACTER*42 FUNCTION ERRORWORDS(IT) !Look for an explanation. One day, the system may offer coherent messages.
Curious collection of encountered codes. Will they differ on other systems?
Line 1,138 ⟶ 1,266:
END IF !But on all systems?
END FUNCTION ERRORWORDS !Hopefully, helpful.
</syntaxhighlight>
</lang>
 
Finally, there is a chance the operating system can be asked to do this, by fragmenting the file in-place into odd-sized pieces. The first piece would be all the records up to the chop, and the second would be all records after resumption. The advantage here is that the rest of the file need no longer be read and written, and files can be large...
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub removeLines(fileName As String, startLine As UInteger, numLines As UInteger)
Line 1,193 ⟶ 1,321:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,219 ⟶ 1,347:
 
=={{header|Frink}}==
Frink's <CODE>array.removeLen[start, len]</CODE> performs this task well.
<lang frink>
<syntaxhighlight lang="frink">removeLines[filename, start, len] :=
{
lines = array[lines["file:$filenameToURL[filename"]]]
modified = lines.removeLen[start-1, len]
if modified != len
Line 1,231 ⟶ 1,359:
w.println[line]
w.close[]
}</syntaxhighlight>
}
</lang>
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">sNewFile As String 'Global string for the 'New file' details
 
Public Sub Main()
Line 1,279 ⟶ 1,406:
Return sNewFile 'Return the details
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,304 ⟶ 1,431:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,375 ⟶ 1,502:
}
return b, true
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
 
<langsyntaxhighlight Groovylang="groovy">static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
Line 1,393 ⟶ 1,520:
}
 
removeLines(args[0], args[1] as Integer, args[2] as Integer)</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.Environment (getArgs)
 
main = getArgs >>= (\[a, b, c] ->
Line 1,403 ⟶ 1,530:
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main() # remove lines
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
Line 1,423 ⟶ 1,550:
close(f)
return # done
end</langsyntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j">removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)</langsyntaxhighlight>
 
Thus:
<langsyntaxhighlight lang="bash">$ cal >cal.txt
$ cat cal.txt
July 2011
Line 1,443 ⟶ 1,570:
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31</langsyntaxhighlight>
 
<langsyntaxhighlight lang="j"> 2 1 removeLines 'cal.txt'</langsyntaxhighlight>
 
<langsyntaxhighlight lang="bash">$ cat cal.txt
1 2
3 4 5 6 7 8 9
Line 1,453 ⟶ 1,580:
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31</langsyntaxhighlight>
 
Note that this code defines the last character in the file as the line end character.
 
=={{header|Java}}==
<syntaxhighlight lang="java">
<lang Java>
import java.io.BufferedReader;
import java.io.File;
Line 1,514 ⟶ 1,641:
}
 
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 1,525 ⟶ 1,652:
then to copy lines from a file named INFILE except for NUMBER lines starting with START,
invoke jq as follows:
<langsyntaxhighlight lang="sh">jq -s -R -r --arg start START --arg number NUMBER -f remove.jq INFILE</langsyntaxhighlight>
 
For example:
 
jq -s -R -r --arg start 1 --arg number 2 -f remove.jq input.txt
<langsyntaxhighlight lang="jq"># Counting the first line in the file as line 1,
# attempt to remove "number" lines from line number "start" onwards:
def remove_lines(start; number):
Line 1,544 ⟶ 1,671:
| (if $count < $max then "WARNING: there are only \($count) lines" else empty end), .;
 
remove_lines($start|tonumber; $number|tonumber)</langsyntaxhighlight>
 
{{works with|jq|1.5}}
Line 1,550 ⟶ 1,677:
 
The command invocation looks like this:
<langsyntaxhighlight lang="sh">jq -n -R -r --arg start 1 --arg number 2 -f Remove_lines_from_a_file.jq input.txt</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq"># Counting the first line in the file as line 1, attempt to remove "number" lines from line
# number "start" onwards:
def remove_lines_streaming(start; number):
Line 1,566 ⟶ 1,693:
end) ;
 
remove_lines_streaming($start|tonumber; $number|tonumber)</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight Julialang="julia">#!/usr/bin/env julia
 
const prgm = basename(Base.source_path())
Line 1,601 ⟶ 1,728:
f = open(file, "w")
write(f, join(lines))
close(f)</langsyntaxhighlight>
 
Usage:
Line 1,636 ⟶ 1,763:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.io.File
Line 1,678 ⟶ 1,805:
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}</langsyntaxhighlight>
 
{{out}}
Line 1,704 ⟶ 1,831:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
 
local(
Line 1,725 ⟶ 1,852:
#file -> dowithclose => {
#file -> writestring(#content -> join(''))
}</langsyntaxhighlight>
Input:
<pre>1 Here is a row
Line 1,734 ⟶ 1,861:
</pre>
Call:
<syntaxhighlight lang Lasso="lasso">./removelines textfile.txt 2 2</langsyntaxhighlight>
Output:
<pre>1 Here is a row
Line 1,743 ⟶ 1,870:
=={{header|Liberty BASIC}}==
It's always a bit dangerous to experiment with code that alters files. Un-rem the 'kill' to remove the temp file and the next line so the file is renamed to the original!
<syntaxhighlight lang="lb">
<lang lb>
call removeLines "foobar.txt", 1, 2
end
Line 1,764 ⟶ 1,891:
'name filename$ + ".tmp" as filename$
end sub
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
Line 1,792 ⟶ 1,919:
 
fp:close()
end</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
Line 1,804 ⟶ 1,931:
Print["Too few lines in document. Operation aborted."]
]
]</langsyntaxhighlight>
 
=={{header|NewLISP}}==
 
<langsyntaxhighlight lang="newlisp">
(context 'ABC)
 
Line 1,844 ⟶ 1,971:
(ABC:remove-lines-from-a-file "foobar.txt" 8 3)
(exit)
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import sequtils, strutils
 
proc removeLines*(filename: string; start, count: Positive) =
 
# Read the whole file, split into lines but keep the ends of line.
var lines = filename.readFile().splitLines(keepEol = true)
 
# Remove final empty string if any.
if lines[^1].len == 0: lines.setLen(lines.len - 1)
 
# Compute indices and check validity.
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
 
# Delete the lines and write the file.
lines.delete(first, last)
filename.writeFile(lines.join())</syntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
Line 1,880 ⟶ 2,028:
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))</langsyntaxhighlight>
 
<pre>$ cal > cal.txt
Line 1,904 ⟶ 2,052:
=={{header|Oforth}}==
 
<langsyntaxhighlight lang="oforth">: removeLines(filename, startLine, numLines)
| line b endLine |
ListBuffer new ->b
Line 1,915 ⟶ 2,063:
drop numLines 0 == ifFalse: [ "Error : Removing lines beyond end of file" println return ]
 
File new(filename) dup open(File.WRITE) b apply(#[ << dup cr ]) close ;</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,923 ⟶ 2,071:
{{works with|Free Pascal|2.6.2}}
 
<langsyntaxhighlight Pascallang="pascal">program RemLines;
 
{$mode objfpc}{$H+}
Line 2,032 ⟶ 2,180:
ReadLn;
End.
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,038 ⟶ 2,186:
 
=={{header|Perl}}==
The value of deleting certain lines from a file notwithstanding, here's how you'd normally do it in Perl (call with <code>perl rmlines -from=3 -to=10 filename</code>:<langsyntaxhighlight lang="perl">#!/usr/bin/perl -n -s -i
print unless $. >= $from && $. <= $to;</langsyntaxhighlight>
If you want a backup file (maybe because deleting lines from a file in place is a pretty silly idea), change the <code>-i</code> in the first line to <code>-i.bak</code>, for example.
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl -w
use strict ;
use Tie::File ;
Line 2,067 ⟶ 2,215:
}
 
deletelines( \@ARGV ) ;</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>procedure remove_lines(string filename, integer start, integer n)
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
integer fn = open(filename,'r')
<span style="color: #008080;">procedure</span> <span style="color: #000000;">remove_lines</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">start</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
if fn!=-1 then
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'r'</span><span style="color: #0000FF;">)</span>
sequence lines = get_text(fn,GT_LF_STRIPPED)
<span style="color: #008080;">if</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">!=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
close(fn)
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"cannot open file!\n"</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">else</span>
if fn=-1 or n<1 or start<1 or length(lines)<start+n-1 then
<span style="color: #004080;">object</span> <span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GT_LF_STRIPPED</span><span style="color: #0000FF;">)</span>
puts(1,"bad parameters!\n")
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
else
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">1</span> <span style="color: #008080;">or</span> <span style="color: #000000;">start</span><span style="color: #0000FF;"><</span><span style="color: #000000;">1</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">start</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
lines[start..start+n-1] = {}
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"bad parameters!\n"</span><span style="color: #0000FF;">)</span>
fn = open(filename,'w')
<span style="color: #008080;">else</span>
puts(fn,join(lines,"\n")
<span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">start</span><span style="color: #0000FF;">..</span><span style="color: #000000;">start</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
close(fn)
<span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'w'</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
end procedure</lang>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<!--</syntaxhighlight>-->
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">"aFile.txt" var fileName
100 var startLine
10 var lineCount
Line 2,114 ⟶ 2,267:
else
"WRONG! error in file operation" print
endif</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de deleteLines (File Start Cnt)
(let L (in File (make (until (eof) (link (line)))))
(if (> (+ (dec 'Start) Cnt) (length L))
Line 2,123 ⟶ 2,276:
(out File
(mapc prinl (cut Start 'L))
(mapc prinl (nth L (inc Cnt))) ) ) ) )</langsyntaxhighlight>
 
=={{header|PowerBASIC}}==
{{works with|PowerBASIC Console Compiler}}
 
<langsyntaxhighlight lang="powerbasic">#DIM ALL
 
FUNCTION PBMAIN () AS LONG
Line 2,164 ⟶ 2,317:
filespec = DIR$
WEND
END FUNCTION</langsyntaxhighlight>
 
Sample output:
Line 2,176 ⟶ 2,329:
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function del-line($file, $start, $end) {
$i = 0
Line 2,188 ⟶ 2,341:
}
del-line "foobar.txt" 1 2
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
; Contents of file 'input.txt' before deletion of lines :
;
Line 2,261 ⟶ 2,414:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
 
{{out|Output ('input.txt' after removal of lines}}
Line 2,274 ⟶ 2,427:
=={{header|Python}}==
Uses the [http://docs.python.org/library/fileinput.html fileinput] standard module.
<langsyntaxhighlight lang="python">#!/usr/bin/env python
 
import fileinput, sys
Line 2,285 ⟶ 2,438:
pass
else:
print line[:-1].rstrip("\n")
fileinput.close()</langsyntaxhighlight>
 
{{out}}
Line 2,315 ⟶ 2,468:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define (remove-lines file from num)
Line 2,321 ⟶ 2,474:
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub MAIN ($filename, $beg, $len) {
my @lines = split /^^/, slurp $filename;
unlink $filename; # or rename
splice(@lines,$beg,$len) == $len or warn "Too few lines";
spurt $filename, @lines;
}</langsyntaxhighlight>
{{out}}
<pre>$ cal >foo
Line 2,355 ⟶ 2,508:
::* &nbsp; the output file non─existence
::* &nbsp; authority to read from (and write to) the file (folder)
<langsyntaxhighlight lang="rexx">/*REXX program reads and writes a specified file and delete(s) specified record(s). */
parse arg iFID ',' N "," many . /*input FID, start of delete, how many.*/
if iFID='' then call er "no input fileID specified." /*oops.*/
Line 2,377 ⟶ 2,530:
/*──────────────────────────────────────────────────────────────────────────────────────*/
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) /*pluralizer.*/</langsyntaxhighlight>
'''output''' when using the input of: &nbsp; <tt> foobar.txt,2,4 </tt>
<pre>
Line 2,406 ⟶ 2,559:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
cStr = read("C:\Ring\bin\filename.txt")
aList = str2list(cStr)
Line 2,420 ⟶ 2,573:
see cStr + nl
write("C:\Ring\bin\filename.txt",cStr)
</syntaxhighlight>
</lang>
Input:
<pre>
Line 2,444 ⟶ 2,597:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'tempfile'
 
def remove_lines(filename, start, num)
Line 2,481 ⟶ 2,634:
remove_lines(filename, start, remove)
teardown(filename)
end</langsyntaxhighlight>
 
{{out}}
Line 2,510 ⟶ 2,663:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">fileName$ = "aFile.txt"
startLine = 100
lineCount = 10
Line 2,523 ⟶ 2,676:
wend
close #in
close #out</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">extern crate rustc_serialize;
extern crate docopt;
 
Line 2,559 ⟶ 2,712:
}
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object RemoveLinesFromAFile extends App {
args match {
case Array(filename, start, num) =>
Line 2,579 ⟶ 2,732:
println("Usage: RemoveLinesFromAFile <filename> <startLine> <numLines>")
}
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "osfiles.s7i";
 
Line 2,612 ⟶ 2,765:
removeLines(argv(PROGRAM)[1], integer parse (argv(PROGRAM)[2]), integer parse (argv(PROGRAM)[3]));
end if;
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">removeLines "foobar.txt", 1, 2
to handle removeLines fileName, startingLine, linesToRemove
If there is no file fileName then
put !"No such file: [[the folder & fileName]]"
Return
End if
set endingLine to startingLine + linesToRemove - 1
If endingLine is more than number of lines in file fileName then
put !"Cannot delete lines past the end of the file ([[number of lines in file fileName]] lines)"
Return
End If
delete lines startingLine to endingLine of file fileName
end removeLines
</syntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func remove_lines(file, beg, len) {
var lines = file.open_r.lines;
lines.splice(beg, len).len == len || warn "Too few lines";
file.open_w.printwrite(lines.join("\n"), :utf8)
}
 
remove_lines(File(__FILE__), 2, 3);</langsyntaxhighlight>
 
=={{header|Snobol4}}==
Line 2,627 ⟶ 2,796:
Developed using the Snobol4 dialect Spitbol for Linux, version 4.0
 
<langsyntaxhighlight Snobol4lang="snobol4">* Remove lines from a file
 
* Function to remove a chunk of lines from a file, will go backward, too, if numlines < 0
Line 2,684 ⟶ 2,853:
end
 
</syntaxhighlight>
</lang>
{{in}}
<pre>1
Line 2,698 ⟶ 2,867:
The usual way to solve this task in Stata consists in removing lines from the currently loaded dataset. This is done with the '''[http://www.stata.com/help.cgi?drop drop]''' command, or alternately with '''keep'''.
 
<langsyntaxhighlight lang="stata">* drop lines 20 to 30
drop in 20/30
 
* keep lines 20 to 30, and remove everything else
keep in 20/30</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc removeLines {fileName startLine count} {
# Work out range to remove
set from [expr {$startLine - 1}]
Line 2,717 ⟶ 2,886:
puts -nonewline $f [join [lreplace $lines $from $to] "\n"]
close $f
}</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$! input=testfile,begnr=3,endnr=4
$$ MODE TUSCRIPT
Line 2,747 ⟶ 2,916:
ENDACCESS/PRINT q
ENDACCESS/PRINT z
</syntaxhighlight>
</lang>
Output:
<pre style='height:30ex;overflow:scroll'>
Line 2,767 ⟶ 2,936:
 
=={{header|UNIX Shell}}==
<langsyntaxhighlight lang="bash">#!/bin/sh
error() {
echo >&2 "$0: $*"
Line 2,783 ⟶ 2,952:
 
sed "$start,${end}d" "$file" >/tmp/$$ && mv /tmp/$$ "$file"
</syntaxhighlight>
</lang>
 
If you have a modern sed on the system, you can use it to do an in-place edit. GNU sed:
 
<langsyntaxhighlight lang="bash">
sed -i "$start,${end}d" "$file"
</syntaxhighlight>
</lang>
 
BSD/MacOS sed:
 
<langsyntaxhighlight lang="bash">
sed -i "" "$start,${end}d" "$file"
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
First way : read the text file line by line
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 2,833 ⟶ 3,002:
End If
End Sub
</syntaxhighlight>
</lang>
 
{{in}}
Line 2,861 ⟶ 3,030:
 
Second Way : Read the text file at once and work with Arrays
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 2,896 ⟶ 3,065:
Close #Nb
End If
End Sub</langsyntaxhighlight>
 
{{in}}
Line 2,924 ⟶ 3,093:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Sub remove_lines(filepath,start,number)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Line 2,956 ⟶ 3,125:
 
Call remove_lines("C:\Test.txt",3,4)
</syntaxhighlight>
</lang>
 
{{in}}
Line 2,989 ⟶ 3,158:
{{trans|Kotlin}}
More or less.
<langsyntaxhighlight ecmascriptlang="wren">import "os" for Platform
import "io" for File
 
Line 3,018 ⟶ 3,187:
}
 
removeLines.call("foobar.txt", 2, 3)</langsyntaxhighlight>
 
{{out}}
Line 3,039 ⟶ 3,208:
Line 8
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">def LF=$0A, EOF=$1A;
 
proc EatLine; \Read and discard a text line from input file
int Ch;
[repeat Ch:= ChIn(3);
if Ch = EOF then
[Text(0, "Attempted to remove a line beyond EOF"); exit];
until Ch = LF;
];
 
proc CopyLine; \Read and write a text line
int Ch;
[repeat Ch:= ChIn(3);
if Ch = EOF then
[Text(0, "Attempted to copy a line beyond EOF"); exit];
ChOut(3, Ch);
until Ch = LF;
];
 
proc RemoveLines(FileName, StartLine, NumLines);
int FileName, StartLine, NumLines;
int N, Ch, IH, OH;
[IH:= FOpen(FileName, 0);
FSet(IH, ^i); \open specified file for input
OpenI(3);
 
OH:= FOpen("file.tmp", 1);
FSet(OH, ^o); \open temporary file for output
OpenO(3);
 
for N:= 1 to StartLine-1 do CopyLine; \copy lines up to start of Start line
for N:= 1 to NumLines do EatLine; \discard NumLines
loop [Ch:= ChIn(3); \copy remainder of input file
if Ch = EOF then quit;
ChOut(3, Ch);
];
Close(3);
FClose(OH); FClose(IH);
 
OH:= FOpen("foobar.txt", 1);
FSet(OH, ^o); \open file for output
OpenO(3);
 
IH:= FOpen("file.tmp", 0);
FSet(IH, ^i); \open temp file for input
OpenI(3);
 
loop [Ch:= ChIn(3); \copy file
if Ch = EOF then quit;
ChOut(3, Ch);
];
Close(3);
];
 
RemoveLines("foobar.txt", 1, 2)
]</syntaxhighlight>
 
=={{header|zkl}}==
Two solutions, one in memory and the other read the file line by line and hope the OS buffers. Write to stdout to avoid "what to use as dst" questions.
<langsyntaxhighlight lang="zkl">fcn deleteLinesM(fname, start,num){
blob:=File(fname).read(); // file to memory
n:=blob.seek(Void,start-1); // seek to line and remember it
Line 3,049 ⟶ 3,276:
File.stdout.write(blob);
}
deleteLinesM("nn.zkl", 2,5);</langsyntaxhighlight>
{{out}}
<pre>
Line 3,057 ⟶ 3,284:
</pre>
Line by line:
<langsyntaxhighlight lang="zkl">fcn deleteLinesL(fname, start,num){
if (start < 1) throw(Exception.ValueError);
f:=File(fname);
Line 3,064 ⟶ 3,291:
f.pump(File.stdout.write);
}
deleteLinesL("nn.zkl", 2,5);</langsyntaxhighlight>
{{out}}
<pre>
1,480

edits