Convert unix one-liner to ruby one-liner

I would like to append a carriage return to all .txt files. I can do it
with unix scripting on the command line, but would like to know what the
equivalent ruby solution is (out of curiosity).

unix solution:
for file in *.txt; do echo >> $file; done

The following also works:

for file in *.txt; do ruby -p -i -e ‘END{puts}’ $file; done

But simplifying to avoid wrapping in a unix script fails to hit any file
except the first from the *.seq list (I don’t understand why, since
usually ruby one-liners can run batch with this input).

ruby -p -i -e ‘END{puts}’ *.txt

Thanks in advance,
Tim

On Sun, Aug 28, 2011 at 9:27 PM, Tim R. [email protected] wrote:

I would like to append a carriage return to all .txt files. I can do it
with unix scripting on the command line, but would like to know what the
equivalent ruby solution is (out of curiosity).

unix solution:
for file in *.txt; do echo >> $file; done

Be careful to use double quotes if there may be spaces in file names.

The following also works:

for file in *.txt; do ruby -p -i -e ‘END{puts}’ $file; done

But simplifying to avoid wrapping in a unix script fails to hit any file
except the first from the *.seq list (I don’t understand why, since

What “*.seq list”?

usually ruby one-liners can run batch with this input).

ruby -p -i -e ‘END{puts}’ *.txt

This cannot work since END is invoked only once. Try instead:

$ ruby -e ‘ARGV.each {|f| File.open(f,“a”) {|io| io.puts}}’ .txt
$ ruby -e 'Dir["
.txt"].each {|f| File.open(f,“a”) {|io| io.puts}}’

You can even do

$ ruby -e ‘ARGV.each {|f| File.open(f,“a”,&:puts)}’ .txt
$ ruby -e 'Dir["
.txt"].each {|f| File.open(f,“a”,&:puts)}’

Kind regards

robert

Robert,
Thanks so much for the quick response and slick suggestions.

ruby -e ‘Dir["*.txt"].each {|f| File.open(f,“a”,&:puts)}’

is my fav.
Thanks,
Tim