在Linux中将一行或多行追加到文件
1. 简介
在本教程中,我们将探索几种使用 Bash 命令在 Linux 中将一行或多行附加到文件的方法。 首先,我们将检查最常见的命令,例如echo、printf和cat。其次,我们将看一下tee命令,这是一个鲜为人知但有用的 Bash 实用程序。
2. echo命令
echo命令 是 Linux Bash最常用和最广泛使用的内置命令之一。通常,我们可以使用它将字符串显示到标准输出,默认为终端:
echo "This line will be displayed to the terminal"
现在,我们将更改默认标准输出并将输入字符串转移到文件中。此功能由重定向运算符 (>) 提供。如果下面指定的文件已经包含一些数据,则数据将丢失:
echo "This line will be written into the file" > file.txt
**为了在file.txt中添加一行而不覆盖其内容,**我们需要使用另一个重定向运算符 (»):
echo "This line will be appended to the file" >> file.txt
请注意,“>”和“»”运算符不依赖于echo命令,它们可以重定向任何命令的输出:
ls -al >> result.txt
find . -type f >> result.txt
此外,我们可以使用*-e选项启用反斜杠转义的解释。因此,将识别一些特殊字符,如**换行符’\n’* ,我们可以将多行附加到文件中:**
echo -e "line3\n line4\n line5\n" >> file.txt
3. printf命令
printf命令 类似于同名的 C 函数。它以以下格式将任何参数打印到标准输出:
printf FORMAT [ARGUMENTS]
让我们构建一个示例并使用重定向运算符将新行添加到我们的文件中:
printf "line%s!" "6" >> file.txt
与echo命令不同,**当我们需要追加多行时,我们可以看到printf的语法更简单。**在这里,我们不必指定特殊选项来使用换行符:
printf "line7\nline8!" >> file.txt
4. cat命令
cat命令 将文件或标准输入连接到标准输出。 它使用类似于echo命令的语法:
cat [OPTION] [FILE(s)]
不同之处在于, cat接受一个或多个文件,而不是字符串作为参数,并将其内容按指定顺序复制到标准输出。 假设我们已经在file1.txt中有一些行,我们想将它们附加到result.txt
cat file1.txt >> result.txt
cat file1.txt file2.txt file3.txt >> result.txt
接下来,我们将从命令中删除输入文件:
cat >> file.txt
在这种情况下,cat命令将从终端读取并将数据附加到file.txt。 因此,让我们在终端中输入一些内容,包括新行,然后按CTRL + D退出:
itcodingman@blogdemo:~/Desktop/blogdemo/append-lines-to-a-file$ cat >> file.txt
line1 using cat command
line2 using cat command
<press CTRL+D to exit>
这将在file.txt的末尾添加两行。
5. tee命令
另一个有趣且有用的 Bash 命令是tee命令 。它从标准输入读取数据并将其写入标准输出和文件:
tee [OPTION] [FILE(s)]
tee file1.txt
tee file1.txt file2.txt
为了将输入附加到文件而不覆盖其内容,我们需要应用-a*选项:*
itcodingman@blogdemo:~/Desktop/blogdemo/append-lines-to-a-file$ tee -a file.txt
line1 using tee command
一旦我们点击Enter,我们实际上会看到我们重复的同一行:
itcodingman@blogdemo:~/Desktop/blogdemo/append-lines-to-a-file$ tee -a file.txt
line1 using tee command
line1 using tee command
这是因为,默认情况下,终端既是标准输入又是标准输出。 我们可以继续输入我们想要的行数,并在每行后按Enter键。我们会注意到每一行都将在终端中重复,并附加到我们的file.txt中:
itcodingman@blogdemo:~/Desktop/blogdemo/append-lines-to-a-file$ tee -a file.txt
line1 using tee command
line1 using tee command
line2 using tee command
line2 using tee command
<press CTRL+D to exit>
现在,假设我们不想将输入附加到终端,而只想附加到文件中。这也可以通过tee命令实现。因此,我们可以使用重定向运算符删除文件参数并将标准输入重定向到我们的file.txt :
itcodingman@blogdemo:~/Desktop/blogdemo/append-lines-to-a-file$ tee >> file.txt
line3 using tee command
<press CTRL+D to exit>
最后,我们来看看file.txt的内容:
This line will be written into the file
This line will be appended to the file
line3
line4
line5
line6
line7
line8
line1 using cat command
line2 using cat command
line1 using tee command
line2 using tee command
line3 using tee command