Remove lines from a file: Difference between revisions
m
→{{header|11l}}: new way of specifying file open mode
MaiconSoft (talk | contribs) (Added Delphi example) |
Alextretyak (talk | contribs) m (→{{header|11l}}: new way of specifying file open mode) |
||
(16 intermediate revisions by 12 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}}==
<
use Ada.Text_IO;
Line 54 ⟶ 60:
"<filename>" & Temporary & " for temporary writing");
Put_Line(" requires first > 0, length >= 0");
end Remove_Lines_From_File;</
=={{header|ALGOL 68}}==
<
# 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</
{{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}}==
<
Loop, Read, %filename%
if ( A_Index < StartingLine )
Line 213 ⟶ 275:
SetWorkingDir, % A_ScriptDir
RemoveLines("test.txt", 4, 3)</
;Output:
with test.txt starting as
Line 232 ⟶ 294:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f REMOVE_LINES_FROM_A_FILE.AWK
# show files after lines are removed:
Line 276 ⟶ 338:
}
}
</syntaxhighlight>
=={{header|BASIC}}==
Line 282 ⟶ 344:
Verbose and with a program loop to test the procedures.
<
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' Remove File Lines V1.1 '
Line 590 ⟶ 652:
END FUNCTION
</syntaxhighlight>
==={{header|IS-BASIC}}===
<
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</
=={{header|C}}==
<
#include <stdlib.h> /* for atoi() and malloc() */
#include <string.h> /* for memmove() */
Line 692 ⟶ 754:
fclose(fp);
return 0;
}</
=={{header|C sharp}}==
{{works with|C sharp|6}}
<
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));
}</
=={{header|C++}}==
<
#include <iostream>
#include <string>
Line 767 ⟶ 829:
return ;
}
}</
=={{header|Clojure}}==
Simple solution dealing with most of the lines in memory.
<
'[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))))</
More complex solution for big file, one line at a time.
<
'[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)))</
=={{header|Common Lisp}}==
<
(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))))</
=={{header|D}}==
<
void main() {
Line 856 ⟶ 918:
f.writeln(line);
}
}</
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
Line 862 ⟶ 924:
===Using TStringDynArray===
<syntaxhighlight lang="delphi">
program Remove_lines_from_a_file_using_TStringDynArray;
Line 886 ⟶ 948:
// Remove 2th & 3td line of file
RemoveLines('input.txt', 1, 2);
end.</
===Using TStringList===
{{libheader| System.SysUtils}}
{{libheader| System.Classes}}
<syntaxhighlight lang="delphi">
program Remove_lines_from_a_file_using_TStringList;
Line 923 ⟶ 985:
// Remove 2th & 3td line of file
RemoveLines('input.txt', 1, 2);
end.</
=={{header|ECL}}==
Implemented for HPCC logical files, not single physical files, since all datasets in HPCC are distributed.
<syntaxhighlight lang="ecl">
IMPORT STD;
RemoveLines(logicalfile, startline, numlines) := FUNCTIONMACRO
Line 935 ⟶ 997:
IF(RecCnt < EndLine,STD.System.Log.addWorkunitWarning('Attempted removal past end of file-removal ignored')));
ENDMACRO;
</syntaxhighlight>
And a simple test case to run:
<syntaxhighlight lang="ecl">
MyFile := DATASET(100,TRANSFORM({UNSIGNED1 RecID},SELF.RecID := COUNTER));
RemoveLines(MyFile,3,10);
</syntaxhighlight>
=={{header|Elixir}}==
<
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
Line 971 ⟶ 1,033:
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)</
{{out}}
Line 990 ⟶ 1,052:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( remove_lines ).
Line 1,020 ⟶ 1,082:
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
</syntaxhighlight>
{{out}}
With "foobar.txt" that looks like this:
Line 1,048 ⟶ 1,110:
=={{header|F_Sharp|F#}}==
<
open System.IO
Line 1,062 ⟶ 1,124:
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0</
Output
<
D:\Projects\Rosetta>Remove_lines_from_a_file.exe foo 1 2
Line 1,073 ⟶ 1,135:
5
D:\Projects\Rosetta></
=={{header|Fortran}}==
Line 1,080 ⟶ 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">
SUBROUTINE CROAK(GASP) !Something bad has happened.
CHARACTER*(*) GASP !As noted.
Line 1,132 ⟶ 1,194:
CALL FILEHACK("foobar.txt",1,2)
END
</syntaxhighlight>
When run on file foobar.txt containing
Line 1,149 ⟶ 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">
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,204 ⟶ 1,266:
END IF !But on all systems?
END FUNCTION ERRORWORDS !Hopefully, helpful.
</syntaxhighlight>
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}}==
<
Sub removeLines(fileName As String, startLine As UInteger, numLines As UInteger)
Line 1,259 ⟶ 1,321:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,285 ⟶ 1,347:
=={{header|Frink}}==
Frink's <CODE>array.removeLen[start, len]</CODE> performs this task well.
<syntaxhighlight lang="frink">removeLines[filename, start, len] :=
{
lines = array[lines[
modified = lines.removeLen[start-1, len]
if modified != len
Line 1,297 ⟶ 1,359:
w.println[line]
w.close[]
}</syntaxhighlight>
=={{header|Gambas}}==
<
Public Sub Main()
Line 1,345 ⟶ 1,406:
Return sNewFile 'Return the details
End</
Output:
<pre>
Line 1,370 ⟶ 1,431:
=={{header|Go}}==
<
import (
Line 1,441 ⟶ 1,502:
}
return b, true
}</
=={{header|Groovy}}==
<
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
Line 1,459 ⟶ 1,520:
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)</
=={{header|Haskell}}==
<
main = getArgs >>= (\[a, b, c] ->
Line 1,469 ⟶ 1,530:
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)</
=={{header|Icon}} and {{header|Unicon}}==
<
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
Line 1,489 ⟶ 1,550:
close(f)
return # done
end</
=={{header|J}}==
<
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)</
Thus:
<
$ cat cal.txt
July 2011
Line 1,509 ⟶ 1,570:
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31</
<
<
1 2
3 4 5 6 7 8 9
Line 1,519 ⟶ 1,580:
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31</
Note that this code defines the last character in the file as the line end character.
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.io.BufferedReader;
import java.io.File;
Line 1,580 ⟶ 1,641:
}
</syntaxhighlight>
=={{header|jq}}==
Line 1,591 ⟶ 1,652:
then to copy lines from a file named INFILE except for NUMBER lines starting with START,
invoke jq as follows:
<
For example:
jq -s -R -r --arg start 1 --arg number 2 -f remove.jq input.txt
<
# attempt to remove "number" lines from line number "start" onwards:
def remove_lines(start; number):
Line 1,610 ⟶ 1,671:
| (if $count < $max then "WARNING: there are only \($count) lines" else empty end), .;
remove_lines($start|tonumber; $number|tonumber)</
{{works with|jq|1.5}}
Line 1,616 ⟶ 1,677:
The command invocation looks like this:
<
<
# number "start" onwards:
def remove_lines_streaming(start; number):
Line 1,632 ⟶ 1,693:
end) ;
remove_lines_streaming($start|tonumber; $number|tonumber)</
=={{header|Julia}}==
<
const prgm = basename(Base.source_path())
Line 1,667 ⟶ 1,728:
f = open(file, "w")
write(f, join(lines))
close(f)</
Usage:
Line 1,702 ⟶ 1,763:
=={{header|Kotlin}}==
<
import java.io.File
Line 1,744 ⟶ 1,805:
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}</
{{out}}
Line 1,770 ⟶ 1,831:
=={{header|Lasso}}==
<
local(
Line 1,791 ⟶ 1,852:
#file -> dowithclose => {
#file -> writestring(#content -> join(''))
}</
Input:
<pre>1 Here is a row
Line 1,800 ⟶ 1,861:
</pre>
Call:
<syntaxhighlight lang
Output:
<pre>1 Here is a row
Line 1,809 ⟶ 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">
call removeLines "foobar.txt", 1, 2
end
Line 1,830 ⟶ 1,891:
'name filename$ + ".tmp" as filename$
end sub
</syntaxhighlight>
=={{header|Lua}}==
<
local fp = io.open( filename, "r" )
if fp == nil then return nil end
Line 1,858 ⟶ 1,919:
fp:close()
end</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
Line 1,870 ⟶ 1,931:
Print["Too few lines in document. Operation aborted."]
]
]</
=={{header|NewLISP}}==
<
(context 'ABC)
Line 1,910 ⟶ 1,971:
(ABC:remove-lines-from-a-file "foobar.txt" 8 3)
(exit)
</syntaxhighlight>
=={{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}}==
<
try Some (input_line ic)
with End_of_file -> None
Line 1,946 ⟶ 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))</
<pre>$ cal > cal.txt
Line 1,970 ⟶ 2,052:
=={{header|Oforth}}==
<
| line b endLine |
ListBuffer new ->b
Line 1,981 ⟶ 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 ;</
=={{header|Pascal}}==
Line 1,989 ⟶ 2,071:
{{works with|Free Pascal|2.6.2}}
<
{$mode objfpc}{$H+}
Line 2,098 ⟶ 2,180:
ReadLn;
End.
</syntaxhighlight>
{{out}}
Line 2,104 ⟶ 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>:<
print unless $. >= $from && $. <= $to;</
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.
<
use strict ;
use Tie::File ;
Line 2,133 ⟶ 2,215:
}
deletelines( \@ARGV ) ;</
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<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>
<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>
<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>
<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>
<span style="color: #008080;">else</span>
<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>
<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;">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>
<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>
<span style="color: #008080;">else</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;">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>
<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>
<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>
<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}}==
<
100 var startLine
10 var lineCount
Line 2,180 ⟶ 2,267:
else
"WRONG! error in file operation" print
endif</
=={{header|PicoLisp}}==
<
(let L (in File (make (until (eof) (link (line)))))
(if (> (+ (dec 'Start) Cnt) (length L))
Line 2,189 ⟶ 2,276:
(out File
(mapc prinl (cut Start 'L))
(mapc prinl (nth L (inc Cnt))) ) ) ) )</
=={{header|PowerBASIC}}==
{{works with|PowerBASIC Console Compiler}}
<
FUNCTION PBMAIN () AS LONG
Line 2,230 ⟶ 2,317:
filespec = DIR$
WEND
END FUNCTION</
Sample output:
Line 2,242 ⟶ 2,329:
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
function del-line($file, $start, $end) {
$i = 0
Line 2,254 ⟶ 2,341:
}
del-line "foobar.txt" 1 2
</syntaxhighlight>
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
; Contents of file 'input.txt' before deletion of lines :
;
Line 2,327 ⟶ 2,414:
CloseConsole()
EndIf
</syntaxhighlight>
{{out|Output ('input.txt' after removal of lines}}
Line 2,340 ⟶ 2,427:
=={{header|Python}}==
Uses the [http://docs.python.org/library/fileinput.html fileinput] standard module.
<
import fileinput, sys
Line 2,351 ⟶ 2,438:
pass
else:
print line
fileinput.close()</
{{out}}
Line 2,381 ⟶ 2,468:
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(define (remove-lines file from num)
Line 2,387 ⟶ 2,474:
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
my @lines = split /^^/, slurp $filename;
unlink $filename; # or rename
splice(@lines,$beg,$len) == $len or warn "Too few lines";
spurt $filename, @lines;
}</
{{out}}
<pre>$ cal >foo
Line 2,421 ⟶ 2,508:
::* the output file non─existence
::* authority to read from (and write to) the file (folder)
<
parse arg iFID ',' N "," many . /*input FID, start of delete, how many.*/
if iFID='' then call er "no input fileID specified." /*oops.*/
Line 2,443 ⟶ 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.*/</
'''output''' when using the input of: <tt> foobar.txt,2,4 </tt>
<pre>
Line 2,472 ⟶ 2,559:
=={{header|Ring}}==
<
cStr = read("C:\Ring\bin\filename.txt")
aList = str2list(cStr)
Line 2,486 ⟶ 2,573:
see cStr + nl
write("C:\Ring\bin\filename.txt",cStr)
</syntaxhighlight>
Input:
<pre>
Line 2,510 ⟶ 2,597:
=={{header|Ruby}}==
<
def remove_lines(filename, start, num)
Line 2,547 ⟶ 2,634:
remove_lines(filename, start, remove)
teardown(filename)
end</
{{out}}
Line 2,576 ⟶ 2,663:
=={{header|Run BASIC}}==
<
startLine = 100
lineCount = 10
Line 2,589 ⟶ 2,676:
wend
close #in
close #out</
=={{header|Rust}}==
<
extern crate docopt;
Line 2,625 ⟶ 2,712:
}
}
}</
=={{header|Scala}}==
<
args match {
case Array(filename, start, num) =>
Line 2,645 ⟶ 2,732:
println("Usage: RemoveLinesFromAFile <filename> <startLine> <numLines>")
}
}</
=={{header|Seed7}}==
<
include "osfiles.s7i";
Line 2,678 ⟶ 2,765:
removeLines(argv(PROGRAM)[1], integer parse (argv(PROGRAM)[2]), integer parse (argv(PROGRAM)[3]));
end if;
end func;</
=={{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}}==
<
var lines = file.open_r.lines
lines.splice(beg, len).len == len || warn "Too few lines";
file.
}
remove_lines(File(__FILE__), 2, 3)
=={{header|Snobol4}}==
Line 2,693 ⟶ 2,796:
Developed using the Snobol4 dialect Spitbol for Linux, version 4.0
<
* Function to remove a chunk of lines from a file, will go backward, too, if numlines < 0
Line 2,750 ⟶ 2,853:
end
</syntaxhighlight>
{{in}}
<pre>1
Line 2,764 ⟶ 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'''.
<
drop in 20/30
* keep lines 20 to 30, and remove everything else
keep in 20/30</
=={{header|Tcl}}==
<
# Work out range to remove
set from [expr {$startLine - 1}]
Line 2,783 ⟶ 2,886:
puts -nonewline $f [join [lreplace $lines $from $to] "\n"]
close $f
}</
=={{header|TUSCRIPT}}==
<
$$! input=testfile,begnr=3,endnr=4
$$ MODE TUSCRIPT
Line 2,813 ⟶ 2,916:
ENDACCESS/PRINT q
ENDACCESS/PRINT z
</syntaxhighlight>
Output:
<pre style='height:30ex;overflow:scroll'>
Line 2,833 ⟶ 2,936:
=={{header|UNIX Shell}}==
<
error() {
echo >&2 "$0: $*"
Line 2,849 ⟶ 2,952:
sed "$start,${end}d" "$file" >/tmp/$$ && mv /tmp/$$ "$file"
</syntaxhighlight>
If you have a modern sed on the system, you can use it to do an in-place edit. GNU sed:
<
sed -i "$start,${end}d" "$file"
</syntaxhighlight>
BSD/MacOS sed:
<
sed -i "" "$start,${end}d" "$file"
</syntaxhighlight>
=={{header|VBA}}==
First way : read the text file line by line
<
Sub Main()
Line 2,899 ⟶ 3,002:
End If
End Sub
</syntaxhighlight>
{{in}}
Line 2,927 ⟶ 3,030:
Second Way : Read the text file at once and work with Arrays
<
Sub Main()
Line 2,962 ⟶ 3,065:
Close #Nb
End If
End Sub</
{{in}}
Line 2,990 ⟶ 3,093:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Sub remove_lines(filepath,start,number)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Line 3,022 ⟶ 3,125:
Call remove_lines("C:\Test.txt",3,4)
</syntaxhighlight>
{{in}}
Line 3,055 ⟶ 3,158:
{{trans|Kotlin}}
More or less.
<
import "io" for File
Line 3,084 ⟶ 3,187:
}
removeLines.call("foobar.txt", 2, 3)</
{{out}}
Line 3,105 ⟶ 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.
<
blob:=File(fname).read(); // file to memory
n:=blob.seek(Void,start-1); // seek to line and remember it
Line 3,115 ⟶ 3,276:
File.stdout.write(blob);
}
deleteLinesM("nn.zkl", 2,5);</
{{out}}
<pre>
Line 3,123 ⟶ 3,284:
</pre>
Line by line:
<
if (start < 1) throw(Exception.ValueError);
f:=File(fname);
Line 3,130 ⟶ 3,291:
f.pump(File.stdout.write);
}
deleteLinesL("nn.zkl", 2,5);</
{{out}}
<pre>
|