Skip to content

Linux 之 cat 和 tee 命令

核心功能对比

命令主要功能典型用途
cat显示文件内容、合并文件、创建文件快速查看文件、连接多个文件、重定向输出
tee同时输出到标准输出(屏幕)和文件记录日志、保存中间结果、多文件备份

cat 命令

基础用法:

shell
# 显示文件内容:
cat file.txt

# 合并文件:
cat file1.txt  file2.txt  > merged.txt

# 创建文件:
cat > newfile.txt
#(输入内容后按 Ctrl+D 保存)

常用选项:

  • -n:显示行号
  • -s:合并连续空行
  • -v:显示非打印字符

tee 命令

基础用法:

  • command:为其它命令,比如 echo, cat 等;
  • |:为管道,会把左边命令的输出传递到右边的命令。
shell
# 同时输出到屏幕和文件:
command | tee output.txt

# 追加内容:
command | tee -a output.txt

# 多文件备份:
command | tee file1.txt  file2.txt

# 高级特性:
# 处理标准错误输出:
command 2>&1 | tee log.txt

典型应用场景

shell
# 实时监控并保存日志
tail -f /var/log/syslog | tee monitor.log

# 数据处理流水线,中间结果保存
cat data.txt | grep "keyword" | tee filtered.txt | sed 's/old/new/' > final.txt

# # 以管理员权限写入文件
echo "password" | sudo tee /etc/secret.conf

结合使用示例

shell
# 通过 cat 输入内容,使用 tee 同时保存到两个文件 
cat <<-EOF | tee file1.txt file2.txt  
This is a test line.
Another line for demonstration.
EOF

通过上述对比和示例,可以清晰看出 cat 适合快速操作文件内容,而 tee 在需要同时记录输出和保留屏幕显示时更具优势。两者结合使用能显著提升数据处理效率。