功能:把一個或者多個文件(或者標準輸入)鏈接在一塊兒,並標準輸出。(Concatenate FILE(s), or standard input, to standard output.)
cat命令經常使用來顯示文件內容,或者將幾個文件鏈接起來顯示,或者從標準輸入讀取內容並顯示。它常與重定向符號配合使用。cat是Concatenate的縮寫。linux
Linux 有三個特別文件,分別
1)標準輸入 即 STDIN , 在 /dev/stdin
通常指鍵盤輸入, shell裏代號是 0
2) 標準輸出 STDOUT, 在 /dev/stdout
通常指終端(terminal), 就是顯示器, shell裏代號是 1
3) 標準錯誤 STDERR, 在 /dev/stderr
也是指終端(terminal), 不一樣的是, 錯誤信息送到這裏
shell裏代號是 2
語法:cat [選項] [文件]
短選項 | 長選項 | 涵義 |
---|---|---|
-A | --show-all | 等於-vET |
-b | --number-nonblank | 對非空輸出行編號 |
-e | 等於-vE | |
-E | --show-ends | 在每行結束處顯示"$" |
-n | --number | 對輸出的全部行編號 |
-s | --squeeze-blank | 不輸出多行空行 |
-t | 與-vT 等價 | |
-T | --show-tabs | 將跳格字符顯示爲^I |
-v | --show-nonprinting | 使用^ 和M- 引用,除了LFD和 TAB 以外 |
輸出文件內容 顯示文件FILE的內容 顯示文件FILE的內容加上行號,須要加上參數-n。行號從1開始。使用-n參數時,全部空行也會顯示行號 忽略掉空行,用-b 當遇到有連續兩行以上的空白行,就代換爲一行的空白行,可使用-s參數 保存內容 將標準輸入保存到文件FILE中,若是文件已經存在,則覆蓋掉原來的 將標準輸入追加到文件FILE末尾 合併文件 將兩個文件FILE1和FILE2的內容合併爲一個文件FILE cat FILEcat -n FILEcat -b FILEcat -s FILEcat >FILEcat >>FILEcat FILE1 FILE2 >FILE
從標準輸入建立文件 [root@web setup]# code>cat >1.txt Hello Bash Linux 鍵盤(快捷鍵)Ctrl+D 保存文件 [root@web setup]# ls -l 1.txt -rw-r--r-- 1 root root 17 11-02 21:32 1.txt [root@web setup]# 顯示1.txt文本內容。標準輸出 Hello Bash Linux [root@web setup]# Hello Bash Linux [root@web setup]# 使用heredoc來生成文件 注意:粗體部分、here doc能夠進行字符串替換 [root@web setup]# <<EOF > Hello > Bash > Linux > PWD=$(pwd) > EOF [root@web setup]# ls -l 2.txt -rw-r--r-- 1 root root 33 11-02 21:35 2.txt [root@web setup]# Hello Bash Linux PWD=/root/setup [root@web setup]# 輸出行號 [root@web setup]# 1 Hello 2 Bash 3 Linux [root@web setup]# nl 1.txt 1 Hello 2 Bash 3 Linux [root@web setup]# 在bash腳本中把文件內容加載到變量中 [root@web ~]# TEXT=$() [root@web ~]# [root@web ~]# echo "$TEXT" # .bash_profile # Get the aliases and functions if [ -f ~/.bashrc ]; then . ~/.bashrc fi # User specific environment and startup programs PATH=$PATH:$HOME/bin export PATH unset USERNAME [root@web ~]#cat 1.txtcat <1.txtcat >2.txtcat 2.txtcat -n 1.txtcat .bash_profile
在linux shell腳本中咱們常常見到相似於cat << EOF的語句,不熟悉的童鞋可能以爲很奇怪:EOF好像是文件的結束符,用在這裏起到什麼做用?EOF是「end of file」,表示文本結束符。web
<<EOF
(內容)
EOFshell
接下來,簡單描述一下幾種常見的使用方式及其做用:bash
# <<EOF > #!/bin/bash > #you Shell script writes here. > EOFcat >test.sh
一、追加文件
# cat <<EOF >>test.sh
spa
二、追加文件,換一種寫法
# cat >>test.sh <<EOF
code
三、EOF只是標識,不是固定的。這裏的「HHH」就代替了「EOF」的功能。結果是相同的。
# cat <<HHH >iii.txt
> sdlkfjksl
> sdkjflk
> asdlfj
> HHHip
四、非腳本中。若是不是在腳本中,咱們能夠用Ctrl+D輸出EOF的標識
# cat >iii.txt
skldjfklj
sdkfjkl
kljkljklj
kljlk
Ctrl+Dci