使用cat和echo在命令列中操作檔案(轉)
阿新 • • 發佈:2019-01-27
誠然,vi等工具也可以在不離開shell的情況下編輯檔案.可此類編輯器始終需要脫離命令列操作.
以下命令是純粹在命令列中執行的,這相較於文字編輯器來說有以下好處:
- 操作更加快捷.
- 便於在bash編寫的shell指令碼中執行.
cat:
cat命令是使用頻率最高的.是concatenate的簡寫. 多用於一次性顯示所有檔案內容.
$ cat file1
新建檔案,並互動式鍵入檔案內容
$ cat > file1 The text you want to type in. <Ctrl-D>
or
$ cat > file1 << EOF > The text you want to type in. > EOF
在互動模式下輸入檔案內容到已存在的檔案尾部
$ cat >> file2 Here type your text appending to the end of file2. <Ctrl-D>
合併檔案,並將合併後內容輸出
$ cat file1 file2
合併檔案,並將合併後內容寫入到新建檔案中
$ cat file1 file2 > newfile
將檔案內容追加到另一個現有檔案的尾部
$ cat file1 >> existing_file
echo
echo主要用來將文字標準化輸出.
輸出文字
$ echo Some string you want to output
輸出系統的環境變數
$ echo $SHELL
新建檔案,並將文字寫入到檔案中
$ echo The text will be added into newfile > newfile
將文字內容追加到現有檔案的尾部
$ echo The text will be appended at the end of the existing file >> existing_file