• Uncategorized

About linux : How-do-I-choose-where-to-output-in-a-file

Question Detail

I have a file like this:

file1:
a aa 
b bb
c cc
file 2: 
d dd ddd
e ee eee

I want to output the contents of file2 to file1, at the line with pattern I choose, like before line with a, after line with b like this:

file 1:
d dd ddd
a aa 
b bb
e ee eee
c cc

I only know how to use puts in tcl or >> with echo in csh, but they only output in last line.

Question Answer

You can use seek to change where the channel points within the file, but that works using byte offsets into the file (the correspondence with characters is complex and depends on the encoding and what the contents really are). It also does not alter the byte offsets of any data that you don’t explicitly rewrite; while that’s often absolutely fine for binary data, it’s a problem with textual data as that usually changes the length of lines when rewritten. (This is inherent in how both POSIX and Windows view files; lots of languages work the same way as a consequence.)

So… for text, you’re actually better off loading all the text into memory, performing the edit there, and then writing the whole file from scratch, as in-place text editing is possible but so immensely awkward that almost nobody does it that way.


The two procedures below are simple stanzas for converting between files and lists of lines of text.

proc linesOfFile {filename} {
    set f [open $filename]
    try {
        return [split [read -nonewline $f] "\n"]
    } finally {
        close $f
    }
}

proc writeLinesToFile {lines filename} {
    set f [open $filename w]
    try {
        puts $f [join $lines "\n"]
    } finally {
        close $f
    }
}

# Read the data
set linesOf1 [linesOfFile file1.txt]
set linesOf2 [linesOfFile file2.txt]

# Do the edits; indices are zero-based
set linesOf1 [linsert $linesOf1 0 [lindex $linesOf2 0]]
set linesOf1 [linsert $linesOf1 3 [lindex $linesOf2 1]]

# Write back
writeLinesToFile $linesOf1 file1.txt

I’ve no idea how to merge the files other than poking the lines in like that; there’s many options, but you’ve kept that info back.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.