From: Andrew Johnson Date: 2006-03-27T07:08:56+09:00 Subject: Re: Ruby-esque approaches to adding a line at the beginning of a file. On Mon, 27 Mar 2006 05:55:30 +0900, Randy Kramer wrote: > On our local lug mail list a discussion came up about using Ruby (as opposed > to Perl) for an application that involved inserting a new line at the front > of an existing file. Well, assuming reading the entire file into memory is acceptable, we can use a fairly standard approach without a temporary file: #!/usr/bin/ruby -w file = 'somefile' first = "new start\n" File.open(file,'r+') do |f| contents = f.read f.seek 0, IO::SEEK_SET f.truncate 0 f.puts first, contents end And, if you like, you can wrap the manipulations with #flock File.open(file,'r+') do |f| f.flock File::LOCK_EX contents = f.read f.seek 0, IO::SEEK_SET f.truncate 0 f.puts first, contents f.flock File::LOCK_UN end Of course, this is a generalized version for any content manipulation you might want to do on the contents, not just adding a new first line. Otherwise, loop over lines, making changes and writing to a temp file, and afterwards, #rename the temp file back to the original. Or, use the command line -i switch: $ cat somefile one two three $ ruby -pi -e 'puts "zero\n" if $. == 1' somefile $ cat somefile zero one two three regards, andrew -- Andrew L. Johnson http://www.siaris.net/ What have you done to the cat? It looks half-dead. -- Schroedinger's wife