From: Paul Duncan Date: 2002-08-01T15:32:20+09:00 Subject: Re: How to make a virtual 2nd column!!! * Kurt Euler (keuler@portal.com) wrote: > All- > > Here's a record formatting question for you: > > Say I have a record like in this format... > > nnnnnThis is a sample sentence meant to demonstrate desired word wrapping to make the appearance of a virtual column from a single long string that doesn't have any hard returns. > > ... and I want to format it to look something like this: > > nnnnn This is a sample sentence meant to > demonstrate desired word wrapping > to make the appearance of a virtual > column from a single long string > that doesn't have any hard returns. > > where: > > - nnnnn is a 5 character string. > - is a tab character (to be replaced by three spaces). > - The first space after every 35 or so characters in the sentence (2nd > field of the record) is replaced by a hard return plus eight spaces. > - The sample above is one of many records in a file, separated by a > hard return. I know you already got one response, but here's another one anyway: -- #!/usr/bin/env ruby def print_record(record, width = 35) # get record identifier id = record.slice! 0..5 # remove delimiting whitespace record.slice! 0..3 # split up record into individual words words = record.split /\s+/ line = id << ' ' while words.length > 0 # append word to current line line << ' ' << words.shift # if current line is past the specified width, # print it out and start a new line puts line or line = ' ' * 7 if line.length > width end # print out last line puts line end # process each file passed on the command-line # (ruby 1.7 can do this in a slightly more concise manner # with File::readlines) ARGV.each { |path| File.open(path) { |file| file.each { |line| print_record(line, 35) } } } -- And the sample data: -- 01234 this is a sample identifier golly look how long this string is hopefully it gets dumped out correctly ladedadeda humdedum. 56789 this is a sample identifier golly look how long this string is hopefully it gets dumped out correctly ladedadeda humdedum. here is an even longer string aslgkjflskdjflksajfl dlska sfdsdf ldfaskjf lkdfjsaljldf salfdkdflskj f fdlkadflf al fdldk jfdkldsfj dsf. -- Gives me the following output: pabs@vault:~/proj/asdf> ./print_record.rb sample.txt 01234 is is a sample identifier golly look how long this string is hopefully it gets dumped out correctly ladedadeda humdedum. 56789 is is a sample identifier golly look how long this string is hopefully it gets dumped out correctly ladedadeda humdedum. here is an even longer string aslgkjflskdjflksajfl dlska sfdsdf ldfaskjf lkdfjsaljldf salfdkdflskj f fdlkadflf al fdldk jfdkldsfj dsf. pabs@vault:~/proj/asdf> > Thanks again, friends! > > -Kurt -- Paul Duncan pabs in #gah (OPN IRC) http://www.pablotron.org/ OpenPGP Key ID: 0x82C29562