如何在Linux Shell脚本输出中插入换行字符
在许多情况下,我们需要在句子中添加换行以格式化输出。在本教程中,我们将探讨一些用于在句子中打印换行字符(\n)的Linux命令。

使用echo
echo命令是用于打印到标准输出的最常用Linux命令之一:
$ echo "test statement \n to separate sentences"
test statement \n to separate sentences
默认情况下,echo将\n视为输入字符串的常规部分。因此,为了使echo命令能够解释换行字符,我们应该使用-e选项:
$ echo -e "test statement \n to separate sentences"
test statement
to separate sentences
注意:默认情况下,无论是否使用-e,echo都会在每个句子的末尾添加\n。
-e选项可能不适用于所有系统和版本。echo的某些版本甚至可以打印-e作为其输出的一部分。因此,我们可以说echo是不可移植的,除非我们省略标志和转义序列,这在这种情况下是无用的。因此,更好的应用方法是使用printf。
使用printf
printf命令还用于将句子打印到标准输出:
$ printf "test statement \n to separate sentences"
test statement
to separate sentences $
与echo不同,printf不需要在句子中启用解释选项。因此,默认情况下,换行字符将应用于句子。
请注意,与echo不同,printf不会自动将\n添加到每个句子的末尾。结果末尾的美元就是因为这个。因此,我们需要在每行末尾手动添加\n:
$ printf "test statement \n to separate sentences \n"
test statement
to separate sentences
printf将在所有系统中工作。注意printf的一个缺点是它的性能。内置的shell echo要快得多。因此,选择一个是可移植性和性能之间的权衡。printf基本上可以实现C版本的功能。因此,我们具有格式化输入字符串的优势。
使用$
自Bash2以来,对$’string’形式的单词进行了特殊处理。所有反斜杠转义字符都将应用于句子。因此,我们可以将此格式与echo和printf一起使用:
$ echo $'test statement \n to separate sentences'
test statement
to separate sentences
我们使用echo是因为printf在默认情况下被解释。注意,我们应该使用单引号来覆盖输入字符串。双引号不起作用。
结论
在本文中,我们描述了如何将\n添加到输出中。
首先,我们使用echo,然后使用printf,这是一个用于添加反斜杠转义字符的更可靠的命令。最后,我们介绍了$’string’格式,它将替换基于ANSI C标准的反斜杠转义字符。