From: Robert Klemme Date: 2005-05-04T22:30:07+09:00 Subject: Re: writing to a file with gsub! Ralf M�ller wrote: > Hi, > > i simply want so change an existing file > > ram@lilith:~/src/ruby$cat test > 123 wer --- > 245545 hzrzu ---- > 245 dfgdfh -- > > > and i thought that > > irb(main):012:0> file = File.open('test'); file.each do |line| > line.gsub!(/\d+/,'###') end > > would do this, because each iterates accross the file. > But nothing is changed. > > Where are my mistakes?? As others have pointed out, reading and writing to the same file at a time is quite complicated. Your approach could only work with memory mapped files... But it's simpler - as simple as ruby -pi.bak -e 'gsub /\d+/, "###"' your_file In case you wonder about the parameter's meanings: 15:23:01 [source]: ruby -h Usage: ruby [switches] [--] [programfile] [arguments] -0[octal] specify record separator (\0, if no argument) -a autosplit mode with -n or -p (splits $_ into $F) -c check syntax only -Cdirectory cd to directory, before executing your script -d set debugging flags (set $DEBUG to true) -e 'command' one line of script. Several -e's allowed. Omit [programfile] -Fpattern split() pattern for autosplit (-a) -i[extension] edit ARGV files in place (make backup if extension supplied) -Idirectory specify $LOAD_PATH directory (may be used more than once) -Kkcode specifies KANJI (Japanese) code-set -l enable line ending processing -n assume 'while gets(); ... end' loop around your script -p assume loop like -n but print line also like sed -rlibrary require the library, before executing your script -s enable some switch parsing for switches after script name -S look for the script using PATH environment variable -T[level] turn on tainting checks -v print version number, then turn on verbose mode -w turn warnings on for your script -W[level] set warning level; 0=silence, 1=medium, 2=verbose (default) -x[directory] strip off text before #!ruby line and perhaps cd to directory --copyright print the copyright --version print the version 15:24:54 [temp]: echo "asdasda123sdasdsd" > your_file 15:25:03 [temp]: cat your_file asdasda123sdasdsd 15:25:11 [temp]: ruby -pi.bak -e 'gsub /\d+/, "###"' your_file 15:25:15 [temp]: cat your_file asdasda###sdasdsd 15:25:16 [temp]: cat your_file.bak asdasda123sdasdsd Kind regards robert