Word wrapping text in a bash script - do you know the best way?

For discussions about programming and projects not necessarily associated with Porteus.
User avatar
Rava
Contributor
Contributor
Posts: 5401
Joined: 11 Jan 2011, 02:46
Distribution: XFCE 5.01 x86_64 + 4.0 i586
Location: Forests of Germany

Word wrapping text in a bash script - do you know the best way?

Post#1 by Rava » 31 Oct 2020, 19:56

Hi folks, I am quite sure I found a solution to that issue some years in the past, but since I created like hundreds (maybe even thousands, who knows, and it not matters anyway) of scripts (mainly sh or bash ones) it would take ages to hunt all these down since they are literally on one of approx 25 USB sticks or 15 external hard drives. :(

My issue is, when the script needs to give a longer text output, it is a mess to manually code that so that no word is cut at the end of line and the rest of that one word is displayed on the next line, instead a nice word wrap is what I (once again) am looking for.
And when one would forcefully and manually pre-wrap the text in the script it would be a waste of space on the right of the terminal if the term $COLUMNS the script runs in is larger that 80 - or if it is less than 80 the text output would still be just cut at the end of lines.

I know there are many ways in archiving this, but for some reason even after long duckduckgo'ing I found nothing that would do what I want and work in both sh or bash, if it only works in bash that would be okay, too.


I hope I made myself clear what I am looking for:


just like the text above, and text in any decent editor when "word wrap" is activated, the words get automatically moved into the next line when the word at the end of a line does not fit into that line.

Here is an example. The info line is a bit longer:

Code: Select all

echo I will also activate the needed dependencies libjpeg.so.8.xzm and libtiff.so.5.xzm . Press enter to continue, or Ctrl+C to abort.
On a 80 cols terminal this looks like so;

Code: Select all

I will also activate the needed dependencies libjpeg.so.8.xzm and libtiff.so.5.x
zm . Press enter to continue, or Ctrl+C to abort.
Instead the output should look like so:

Code: Select all

I will also activate the needed dependencies libjpeg.so.8.xzm and 
libtiff.so.5.xzm . Press enter to continue, or Ctrl+C to abort.
The best solution would wrap the text not hard coded at 80 cols but according to the actual cols the script runs in.

Is it possible to archive that via fold when using a here document? Unfortunately I am not that well versed in the use of here documents. :cry: So I would need some tips from you folks. :Rose:
Last edited by Rava on 31 Oct 2020, 20:19, edited 1 time in total.
Reason: added real life example
Cheers!
Yours Rava