Contents

用于将多行追加到文件的Linux命令

1. 概述

在这个快速教程中,我们将看看如何使用我们的命令 shell 提供的工具将多行字符串附加到文件中。 为简单起见,我们将在所有示例中使用相同的测试数据集:

The customer is very important, the customer will be followed by the customer,
but at such a time they occur as with great labor and pain.

本教程中使用的命令在Bash 中进行了测试,但也应在其他符合 POSIX 的 shell 中工作,除非另有说明。

2. echo

我们可以重定向echo 的输出,并使用重定向运算符»*将其附加到我们的文件中。当文件不存在且不为空时,将自动插入新行

因此,我们的问题的一个天真的解决方案是调用echo两次,对于我们需要附加的每一行调用一次:

echo The customer is very important, the customer will be followed by the customer, >> target.txt
echo but at such a time they occur as with great labor and pain. >> target.txt

让我们进一步简化这一点,并通过显式插入换行符*\n*。我们使用*-e*参数来强制评估,这是我们在脚本中执行语句时所必需的:

echo -e The customer is very important, the customer will be followed by the customer,\\nbut at such a time \
they occur as with great labor and pain. >> target.txt

在上面的例子中,我们必须用另一个*\明确地转义*。但是,我们可以通过用双引号将字符串括起来来避免这种情况,这被认为是最佳实践:

echo -e "The customer is very important, the customer will be followed by the customer,\nbut at such a time \
they occur as with great labor and pain." >> target.txt

重要的是要注意echo命令有一个严重的缺点。许多 shell 提供了自己的echo版本。因此,实现并不总是与 POSIX 兼容,并且在 shell 之间可能有所不同

3. printf

现在让我们看一下printf 命令。此命令在每个 POSIX 兼容的 shell 中的工作方式相同,并且可以以与echo相同的方式使用

printf "The customer is very important, the customer will be followed by the customer,\nbut at such a time \
they occur as with great labor and pain." >> target.txt

此外,printf命令更高级,也可用于格式化字符串。

它类似于同名的 C 函数。例如,我们可以像这样使用 C 风格的字符串格式:

printf "%s\n%s" "The customer is very important, the customer will be followed by the customer," \
"but at such a time they occur as with great labor and pain."

有关格式化字符串的更多信息可以在综合手册页 中找到。

4. cat

我们的问题有一些不太明显的解决方案。 例如,我们可以使用cat 命令将行附加到文件中。通常,我们使用此命令连接文件并将其内容打印到标准输出。

但是,如果我们省略 file 参数,cat将从标准输入中读取输入。然后我们可以使用cat来追加文本:

cat << EOF >> target.txt
The customer is very important, the customer will be followed by the customer,
but at such a time they occur as with great labor and pain.
EOF

在这个例子中,« EOF意味着我们希望cat从标准输入中读取,直到它遇到只包含文本EOF(文件结尾)的行。同样,cat的输出以与前面示例相同的方式写入target.txt,使用*»*重定向运算符。

5. tee

简单地说,tee 命令接受标准输入并将其复制到标准输出,同时将其复制到零个或多个文件中。我们可以像以前使用cat一样使用tee

例如,我们可以告诉tee将(-a)标准输入附加到我们的文件中,直到遇到EOF

tee -a target.txt << EOF
The customer is very important, the customer will be followed by the customer,
but at such a time they occur as with great labor and pain.
EOF