Version 8 of How do I remove one line from a file?

Updated 2006-12-29 19:06:13

How do you delete one line from a file? What kind of file are you talking about? There aren't, in general, lines in MP3 files, or GIF files, etc. In fact, most operating systems today don't have operating system calls that deal in lines. Instead, they come with what I have named, at times, "meta-read" functions - pieces of code which read in chunks of bytes from a file, and then, depending on the function's intention, add some code implementing a common interpretation of some of those bytes.

Most people, asking this particular question, are really asking "Assume that I have a plain, traditional, text file - containing 7 bit ASCII characters, where newline character indicate the end of a "line". How can I delete one of those "lines" ."

And honestly, I really believe that's what is being asked. So the following attempts to address that specific interpretation of this question.


Well, you could use sed. Or you could use something like the following code.


    set tmpname /tmp/something

    set source [open $filename]
    set destination [open $tmpname w]
    set content [read $source]
    close $source
    set lines [split $content \n]
    set lines_after_deletion \
       [lreplace $lines $line_number_to_remove $line_number_to_remove]
    puts -nonewline $destination [join $lines_after_deletion \n]
    close $destination
    file rename -force $destination $source

Note, however, that in both of these cases, what you are doing are reading the entire file and writing out the entire file, counting lines.


RS: Here is a case where awk is simpler than if we do it in Tcl. Say, you want all but the 4th line:

 gawk 'NR!=4' infile > outfile

Category Example - Category File