linux命令详解:cat命令

转:http://www.cnblogs.com/lwgdream/archive/2013/11/06/3409802.html

前言

cat命令用于读取文本文件,并且能够显示行号、特殊字符等。

使用说明

-n 对每行进行编号,包括空行

-b 对每行进行编号,不包括空行

-s 压缩连续的空行

-A 显示特殊字符,换行符、制表符等

使用举例

cat 读取文本文件

   1: [root@master lianxi]# cat f
   2: # Generated automatically from man.conf.in by the
   3: # configure script.

cat 从标准输入读取

通过管道读取其命令的输出,cmd | cat -

   1: [root@master lianxi]# echo "hello world" | cat
   2: hello world
   3: [root@master lianxi]# echo "hello world" | cat -
   4: hello world

-A 显示特殊字符

换行符$、制表符^I

   1: [root@master lianxi]# cat f
   2: # Generated automatically from man.conf.in by the
   3: # configure script.     config
   4: [root@master lianxi]# cat -A f
   5: # Generated automatically from man.conf.in by the$
   6: # configure script.^Iconfig$

添加行号

-n 每行都添加行号,包括空行

   1: [root@master lianxi]# cat -n f
   2:      1  # Generated automatically from man.conf.in by the
   3:      2
   4:      3  # configure script.     config

-b 除了空行,其他每行都加上行号

   1: [root@master lianxi]# cat -b f
   2:      1  # Generated automatically from man.conf.in by the
   3:  
   4:      2  # configure script.     config

-s 压缩连续空行

如下,该文件有3个连续的空行,被压缩成了一个

   1: [root@master lianxi]# cat -n f
   2:      1  # Generated automatically from man.conf.in by the
   3:      2
   4:      3
   5:      4
   6:      5  # configure script.     config
   7: [root@master lianxi]# cat -s -n f
   8:      1  # Generated automatically from man.conf.in by the
   9:      2
  10:      3  # configure script.     config

合并文件

cat f1 f2

   1: [root@master lianxi]# cat f 
   2: # Generated automatically from man.conf.in by the
   3:  
   4:  
   5:  
   6: # configure script.     config
   7: [root@master lianxi]# cat f1
   8: # Generated automatically from man.conf.in by the
   9: # configure script.     config
  10: [root@master lianxi]# cat f f1
  11: # Generated automatically from man.conf.in by the
  12:  
  13:  
  14:  
  15: # configure script.     config
  16: # Generated automatically from man.conf.in by the
  17: # configure script.     config

cat f1 – f2  表示从标准输入读取

cat 是一次读取多个文件,先读取f1,再从 – (标准输入读取),在读取f2

   1: [root@master lianxi]# cat f
   2: lwg
   3: [root@master lianxi]# cat f1
   4: yangzhen
   5: [root@master lianxi]# echo "love" | cat f - f1
   6: lwg
   7: love
   8: yangzhen

 

特殊说明

1)cat读取的是文本文件,读取文件文件肯定会因为无法“正确”解码而出现乱码

2)cat 读取文本文件的时候,是按照系统默认的编码方式来进行解码的。如果文本文件本身编码和默认编码不一致,可能也会出现乱码。可以先通过iconv命令来进行转码

3)cat命令读取多个是顺序依次读取的

总结

用cat命令来读取文本文件,也是linux中最常用的命令之一。

原文地址:https://www.cnblogs.com/pengdonglin137/p/3416774.html