cat 查看文件内容

作用

cat 命令来自于英文单词 concatenate(/[kɒnˈkætɪˌneɪt]/ 连接,连结,使连锁)的缩写,其功能是用于查看文件内容。在 Linux 系统中有很多用于查看文件内容的命令,例如 more、tail、head……等等,每个命令都有各自的特点。

cat 命令适合查看内容较少的、纯文本的文件。对于内容较多的文件,使用 cat 命令查看后会在屏幕上快速滚屏,用户往往看不清所显示的具体内容,只好按 Ctrl+C 键中断命令的执行,所以对于大文件,建议用 more 命令。

cat 命令除了查看文件内容,如果从标准输入设备读入数据并将结果重定向到一个新的文件中,则可以达到建立新文件的目的。

cat 命令在编辑新的文件时只能从键盘接收数据,不能灵活地对文件的内容进行编辑,灵活性远远不如专门的文本编辑工具,如:vim、emacs 等。

语法

cat [-AbeEnstTuv] [--help] [--version] fileName

参数

  • -n  显示行数(空行也编号)

  • -s  显示行数(多个空行算一个编号)

  • -b  显示行数(空行不编号)

  • -E  每行结束处显示$符号

  • -T  将TAB字符显示为 ^I符号

  • -v  使用 ^ 和 M- 引用,除了 LFD 和 TAB 之外

  • -e  等价于”-vE”组合

  • -t  等价于”-vT”组合

  • -A  等价于 -vET组合

  • --help  显示帮助信息

  • --version  显示版本信息

示例

(1)使用 cat 命令创建一个名为 new.txt 的新文件

[hxstrive@localhost ~]$ cat > new.txt
hello world^C
[hxstrive@localhost ~]$ ll new.txt 
-rw-rw-r--. 1 hxstrive hxstrive 0 May 26 22:35 new.txt

用户可以从标准输入为该文件录入内容,按 Ctrl + C 命令退出编辑。再用 ll 命令查看新创建文件的属性。

(2)对已存在的文件追加新的内容

# 查看 new.txt 文件内容
[hxstrive@localhost ~]$ cat new.txt
hello world

# 向  new.txt 文件追加新内容
[hxstrive@localhost ~]$ cat >> new.txt
new content
^C

# 查看最终效果
[hxstrive@localhost ~]$ cat new.txt 
hello world
new content

(3)使用 -n 选项显示行号

[hxstrive@localhost ~]$ cat -n demo.txt 
     1	Hold fast to dreams
     2	For if dreams die
     3	Life is a broken-winged bird
     4	That can never fly
     5	
     6	
     7	Hold fast to dreams
     8	For when dreams go
     9	Life is a barren field
    10	Frozen only with snow
    11	

(4)使用 -b 选项显示行数,空行不进行编号

[hxstrive@localhost ~]$ cat -b demo.txt 
     1	Hold fast to dreams
     2	For if dreams die
     3	Life is a broken-winged bird
     4	That can never fly


     5	Hold fast to dreams
     6	For when dreams go
     7	Life is a barren field
     8	Frozen only with snow

更多关于命令详细参考手册,请使用 man 命令或者 --help 参数获取帮助信息

关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号