cat
命令的用途是连接文件或标准输入并打印。这个命令常用来显示文件内容,或者将几个文件连接起来显示,或者从标准输入读取内容并显示,它常与重定向符号配合使用。
1.命令格式
cat [选项] [文件]…
2.命令功能
cat
主要有三大功能:
- 一次显示整个文件:
cat filename
- 从键盘创建一个文件:
cat > filename
只能创建新文件,不能编辑已有文件. - 将几个文件合并为一个文件:
cat file1 file2 > file
命令参数:-A
,--show-all
等价于-vET
-b
,--number-nonblank
对非空输出行编号-e
等价于-vE
-E
,--show-ends
在每行结束处显示$
-n
,--number
对输出的所有行编号,由1开始对所有输出的行数编号-s
,--squeeze-blank
有连续两行以上的空白行,就代换为一行的空白行-t
与-vT
等价-T
,--show-tabs
将跳格字符显示为^I
-u
(被忽略)-v
,--show-nonprinting
使用^
和M-
引用,除了LFD
和TAB
之外
4.使用实例
实例一
把 mylog1.log
的文件内容加上行号后输入 mylog2.log
这个文件里。
命令:
cat -n mylog1.log mylog2.log
输出:
[zaixian@localhost test]$ cat mylog1.log
this is line 1
this is line 2
[zaixian@localhost test]$ cat mylog2.log
log2 this is line 1
log2 this is line 2
log2 this is line 3
[zaixian@localhost test]$ cat -n mylog1.log mylog2.log
1 this is line 1
2 this is line 2
3 log2 this is line 1
4 log2 this is line 2
5 log2 this is line 3
[zaixian@localhost test]$
实例二
把 mylog1.log
和 mylog2.log
的文件内容加上行号(空白行不加)之后将内容附加到 log.log
里。
命令:
cat -b mylog1.log mylog2.log log.log
输出:
zaixian@localhost test]$ cat -b mylog1.log mylog2.log >> log.log
[zaixian@localhost test]$ cat log.log
1 this is line 1
2 this is line 2
3 log2 this is line 1
4 log2 this is line 2
5 log2 this is line 3
[zaixian@localhost test]$
实例三
使用here doc来生成文件
[zaixian@localhost test]$ cat >log.txt <<EOF
> Hello
> World
> Linux command
> PWD=$(pwd)
> EOF
[zaixian@localhost test]$ ls -l log.txt
-rw-rw-r--. 1 zaixian zaixian 49 Feb 13 03:20 log.txt
[zaixian@localhost test]$ cat log.txt
Hello
World
Linux command
PWD=/home/zaixian/test
[zaixian@localhost test]$