Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Splitting text into lines

Status
Not open for further replies.

wxb2744

Technical User
Jan 23, 2008
9
0
0
EU
Hi,

This is more a challenge then a question really.

I'm wanting to print some long lines out to a terminal, but I don't want the terminal to cut words in half as they wrap to the next line. Essentially I want to be able to split on the last word boundary before, say, 80 characters. I cannot pre-format the text as the terminal width is not guaranteed to be the same.

I want to, for example, to do this: -
Code:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis 
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu 
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in 
culpa qui officia deserunt mollit anim id est laborum
instead of this: -
Code:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis [red][b]nostr
ud[/b][/red] exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis [red][b]au
te[/b][/red] irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat 
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa [red][b]qu
i[/b][/red] officia deserunt mollit anim id est laborum
I've already got some code that does it, but it is clunky and horrible. I'm looking for something simpler and more elegant.

Thanks,

Warren
 
Thanks feherke, but I spent most of yesterday looking into it and I got the code down to: -

Code:
[blue]my $[/blue]text = "[COLOR=gray]Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.[/color]";

[blue]my $[/blue]width = [red]80[/red] - [red]1[/red]; [green]# 80 just for example[/green]
[red]print[/red] "[gray]$_\n[/gray]" [red]for[/red] [blue]$[/blue]text =~ /\s?(.{[red]1[/red],[blue]$[/blue]width})(?=\s|$)/g;

Warren
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top