1. 理解I/O重定向的基本概念
1.1 输入重定向
在Linux系统中,输入重定向是指将命令的输入从键盘改变为来自文件或其他命令的输出。使用 <
符号可以实现输入重定向,例如:
$ command < input.txt
这将使command
命令从input.txt
文件中读取输入而不是从键盘。
1.2 输出重定向
输出重定向是将命令的输出从屏幕改变为保存到文件或传递给其他命令。使用 >
符号可以实现输出重定向,例如:
$ command > output.txt
这将把command
命令的输出保存到output.txt
文件中。
2. 实际应用:使用I/O重定向提高效率
2.1 输出重定向的应用
2.1.1 保存命令输出
通过输出重定向,我们可以将命令的输出保存到文件中,方便后续查看或分析。
$ ls -l > file_list.txt
这将列出当前目录下的文件,并将结果保存到file_list.txt
文件中。
2.1.2 追加输出到文件
如果需要将命令输出追加到文件而不是覆盖文件,可以使用 >>
符号。
$ echo "New content" >> existing_file.txt
3. 综合案例:利用重定向建立多行文件和脚本中的消息打印
3.1 利用重定向建立多行文件
有时候我们需要创建一个包含特定内容的多行文件,可以使用重定向和 Here 文档来实现。
$ cat <<EOF > multiline_file.txt Line 1: This is the first line. Line 2: Here is the second line. Line 3: And finally, the third line. EOF
上述命令使用 Here 文档(以 <<EOF
开始,以 EOF
结束)将多行文本重定向到multiline_file.txt
文件中。
3.2 在脚本中利用重定向打印消息
3.2.1 创建脚本文件
创建一个简单的 Bash 脚本文件(例如 print_messages.sh
),其中包含如下内容:
#!/bin/bash echo "This is a message to standard output." echo "This is an error message to standard error." >&2
3.2.2 运行脚本并重定向输出
运行脚本,并将标准输出和标准错误分别重定向到不同的文件:
$ ./print_messages.sh > output.log 2> error.log
这将把标准输出保存到output.log
文件中,将标准错误保存到error.log
文件中。
3.2.3 合并标准输出和标准错误到同一文件
如果希望将标准输出和标准错误合并到同一个文件中,可以使用 2>&1
:
$ ./print_messages.sh > combined_output_and_error.log 2>&1
这将把标准输出和标准错误都保存到combined_output_and_error.log
文件中。
$ cat <<EOF > multiline_file.txt Line 1: This is the first line. Line 2: Here is the second line. Line 3: And finally, the third line. EOF
bash$ cat <<EOF > multiline_file.txt Line 1: This is the first line. Line 2: Here is the second line. Line 3: And finally, the third line. EOF
bash
Echo ‘111’ >file03.txt
Cat > file03.txt
bash
$ ls -l > file_list.txt
Echo ‘111’ >file03.txt
Cat > file03.txt
bash
Echo ‘111’ >file03.txt Cat > file03.txt
标签:文件,重定向,输出,读书笔记,Linux,Line,txt,line
From: https://www.cnblogs.com/ppwqdsx/p/17845170.html