天天看點

【Linux】一步一步學Linux——cat/tac指令(38)

00. 目錄

文章目錄

    • 00. 目錄
    • 01. 指令概述
    • 02. 指令格式
    • 03. 常用選項
    • 04. 參考示例
    • 05. 附錄

01. 指令概述

将[檔案]或标準輸入組合輸出到标準輸出。

cat 指令連接配接檔案并列印到标準輸出裝置上,經常用來顯示整個檔案的内容。cat 隻能檢視文本内容的檔案,如檢視二進制檔案,則螢幕會顯示亂碼。另外,cat 還可以用來建立檔案、合并檔案等。

02. 指令格式

用法:cat [選項] [檔案]...
           

03. 常用選項

将檔案清單中的檔案或标準輸入連接配接到标準輸出。
-A, --show-all
	等價于 -vET 。
-b, --number-nonblank
	給非空輸出行編号。
-e     等價于 -vE 。
-E, --show-ends
	在每行結束顯示 $ 。
-n, --number
	給所有輸出行編号。
-s, --squeeze-blank
	将所有的連續的多個空行替換為一個空行。
-t     等價于 -vT 。
-T, --show-tabs
	把 TAB 字元顯示為 ^I 。
-u     (被忽略的選項)
-v, --show-nonprinting
	除了 LFD 和 TAB 之外所有控制符用 ^ 和 M- 記方式顯示。
--help 顯示幫助并退出。
--version
	顯示版本資訊并退出。
	沒有指定檔案或指定的檔案是 -,則從标準輸入讀取。
           

04. 參考示例

4.1 檢視檔案的内容

[[email protected] test]$ cat /etc/passwd
           

4.2 檢視檔案的内容,并顯示行數編号

[[email protected] test]$ cat -n /etc/passwd
           

4.3 檢視檔案的内容,并添加行數編号後輸出到另外一個檔案中

[[email protected] test]$ cat -n /etc/passwd > file.txt
           

4.4 清空檔案的内容

[[email protected] test]$ cat /dev/null > file.txt
[[email protected] test]$ cat file.txt 
[[email protected] test]$ 
           

4.5 持續寫入檔案内容,碰到EOF符後結束并儲存

[[email protected] test]$ cat > file.txt
hello itcat
神馬程式員
EOF
[[email protected] test]$ 
           

4.6 将軟碟裝置制作成鏡像檔案

[[email protected] test]$ cat /dev/fd0 > disk.iso
           

4.7 将所有的連續的多個空行替換為一個空行

有時候檔案中空行會很多,如果要将多個空行合并為一個,使用

-s

選項。

[[email protected] test]$ cat -s file.txt 
           

4.8 将所有的連續的多個空行替換為一個空行,并且所有輸出行編号

[[email protected] test]$ cat -ns file.txt 
     1  hello itcat
     2
     3  神馬程式員
     4
     5  EOF
[[email protected] test]$ 
           

4.9 對非空輸出行編号

若要對非空行進行編号,空行不編号,使用

-b

選項。

[[email protected] test]$ cat -b file.txt 
     1  hello itcat



     2  神馬程式員

     3  EOF
[[email protected] test]$ 
           

4.10 在每行結束處顯示 $

[[email protected] test]$ cat -E file.txt 
hello itcat$
$
$
$
神馬程式員$
$
EOF$
[[email protected] test]$ 
           

4.11 合并檔案内容

[[email protected] test]$ cat /etc/passwd a.txt > file.txt
           

4.12 建立新檔案

按 Ctrl-D結束

[[email protected] test]$ cat > test.sh
#!/bin/bash
echo "hello world"
[[email protected] test]$ 
           

4.13 複制檔案

使用 cat 還可以複制檔案,包括文本檔案、二進制檔案或 ISO CD光牒檔案等。

[[email protected] test]$ cat file.txt > file1.txt
[[email protected] test]$ md5sum file.txt file1.txt 
aaa72d9a30499cc66e1325f3699bf5f6  file.txt
aaa72d9a30499cc66e1325f3699bf5f6  file1.txt
[[email protected] test]$ 
           

4.14 插入多行

将制定内容添加的檔案 jackonill.txt 當中,當輸入EOF後指令結束。

注意:EOF可用其他字元代替。

[[email protected] test]$ cat >> file.txt  << EOF
> 神馬程式員
> 俠客
> 知識
> EOF
[[email protected] test]$ 
           

溫馨提示

tac 是将 cat 反寫過來,是以他的功能就跟 cat 相反, cat 是由第一行到最後一行連續顯示在螢幕上,而 tac 則是由最後一行到第一行反向在螢幕上顯示出來!

05. 附錄

參考:【Linux】一步一步學Linux系列教程彙總

繼續閱讀