工作上对于cat的使用,最多的还是当做查看文件或是日记的命令,例如cat app.log,其实这个并不是cat自身最核心的功能,cat本身的含义就是拼接,不过是被误用为查看比较多,那就先看看它的第一个功能吧。
拼接
生成两个文件
inter12@inter12-VirtualBox:/tmp/shell$ touch {1..2} inter12@inter12-VirtualBox:/tmp/shell$ ls 1 2
分别给两个文件添加点内容。
inter12@inter12-VirtualBox:/tmp/shell$ echo "this is first file" > 1 inter12@inter12-VirtualBox:/tmp/shell$ echo "this is second file" > 2 inter12@inter12-VirtualBox:/tmp/shell$ more 1 this is first file inter12@inter12-VirtualBox:/tmp/shell$ more 2 this is second file
拼接文件:
inter12@inter12-VirtualBox:/tmp/shell$ cat 1 2 this is first file this is second file
上面这个例子是从文件中读取内容进行拼接,它也可以从标准输入中进行读取
inter12@inter12-VirtualBox:/tmp/shell$ echo "add new info to file 1 " | cat - 1 add new info to file 1 this is first file
-:表示从标准输入的文件名 ,本质上就是将- 和 1 进行了拼接,若是换个位置看
inter12@inter12-VirtualBox:/tmp/shell$ echo "add new info to file 1 " | cat 1 - this is first file add new info to file 1
内容就是加到后面了。这里延伸的说,若是想给文件添加内容的话,同样可以使用sed命令来搞,看看实战
inter12@inter12-VirtualBox:/tmp/shell$ sed 'a1 add by sed command' 1 this is first file 1 add by sed command inter12@inter12-VirtualBox:/tmp/shell$ sed 'i1 add by sed command' 1 1 add by sed command this is first file
第一个命令代表从文件1的第一行后面添加一行数据,第二个从第一行的前面插入一个数据。sed还是非常无比的强大的。
查看的辅助功能:
去除连续的空行
inter12@inter12-VirtualBox:/tmp/shell$ cat cat.txt hello world hoho haha heihei inter12@inter12-VirtualBox:/tmp/shell$ cat -s cat.txt hello world hoho haha heihei
-s:去除连续的空行
延伸的说,想去除所有的空行的办法
第一种采用tr
inter12@inter12-VirtualBox:/tmp/shell$ cat cat.txt | tr -s '\n' hello world hoho haha heihei
第二种还是采用 sed命令
inter12@inter12-VirtualBox:/tmp/shell$ sed '/^$/d' cat.txt hello world hoho haha heihei
删除所有的空行
显示行号:
inter12@inter12-VirtualBox:/tmp/shell$ cat -n cat.txt 1 hello world 2 3 4 hoho 5 6 haha 7 8 heihei
只显示有数据的行号:
inter12@inter12-VirtualBox:/tmp/shell$ cat -b cat.txt 1 hello world 2 hoho 3 haha 4 heihei
若是想去除空行且显示行号:
inter12@inter12-VirtualBox:/tmp/shell$ sed '/^$/d' cat.txt | cat -n 1 hello world 2 hoho 3 haha 4 heihei
还有个较少适用的就是将文件中的制表符用^|来显示,主要是为了在一种编辑器中编写脚本时使用制表符,换了另一个编辑器容易格式混乱,采用cat命令可以找出那些适用了制表符的地方。
inter12@inter12-VirtualBox:/tmp/shell$ cat -T fun #/bin/bash def test_function(){ ^Iecho "tab" echo "blank" }
我在第一个echo处用了tab,所以显示的时候是^I,能够很清晰找出制表符。
总结下吧:cat的主要功能是连接多个文件+查看文件
0 条评论。