2016-12-02 45 views
1

我在写一个非常简单的bash脚本,询问包含以前答案的文本。例如:如何使用硬线换行回显字符串?

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" 

其中一些问题相当长。 echo的输出在我的macOS终端窗口中进行软包装,但是通过字符而不是单词。如何通过单词将输出硬编码为特定的字符宽度?

我无法手动添加中断到$questionText,因为包含的变量可以是任意长度。

我的搜索全部引导我到fmtfold,但那些想要文本文件作为输入,而不是变量。

我在找的东西就像echo,但有一个选项可以将输出转换为指定的宽度。

回答

3

我的搜索全部引导我到fmtfold,但那些想要文本文件作为输入,而不是变量。

只需使用管道:

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

使用-s选项将使fold只在空白字符包,而不是在一个单词中间:

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

谢谢!比我使用'tmp.txt'文件的解决方法好得多。 –

+0

此外请注意,您可以使用[here string](https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Here-Strings):'fold <<<“$ {questionText} “' – hek2mgl