cat命令

cat命令的用途是連接檔或標準輸入並列印。這個命令常用來顯示檔內容,或者將幾個檔連接起來顯示,或者從標準輸入讀取內容並顯示,它常與重定向符號配合使用。

1.命令格式

cat [選項] [檔]…

2.命令功能

cat主要有三大功能:

  1. 一次顯示整個檔:cat filename
  2. 從鍵盤創建一個檔:cat > filename 只能創建新檔,不能編輯已有檔.
  3. 將幾個檔合併為一個檔: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- 引用,除了 LFDTAB 之外

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.logmylog2.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]$

上一篇: touch命令 下一篇: nl命令