Stu Maschwitz
Stu Maschwitz

Reputation: 73

How can I echo a string with hard line wrap?

I am writing a very simple bash script that asks questions that include text from previous answers. For example:

questionText="Hi $userName, I'm going to ask you some questions. At the end of the process, I'll output a file that might be helpful to you."
echo "$questionText"

Some of these questions are quite long. The output from echo soft-wraps in my macOS Terminal window, but by character rather than by word. How do I hard-wrap the output to a specific width in characters, by word?

I can't manually add the breaks to $questionText because the included variables could be any length.

My searches all lead me to fmt and fold, but those want text files as input, not variables.

What I'm looking for is something like echo, but with an option to word wrap the output to a specified width.

Upvotes: 7

Views: 6673

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47119

My searches all lead me to fmt and fold, but those want text files as input, not variables.

Just use a pipe:

printf '%s\n' "$questionText" | fold

Using the -s option will make fold only wrap on white space characters, and not in the middle of a word:

printf '%s\n' "$questionText" | fold -s

Upvotes: 16

Related Questions