檔案編輯:向檔案追加不存在的行
有時需要向檔案追加一行或字串以更改輸出而無需刪除現有資料。這是一種透過在檔案的現有行之間新增多行來修改檔案的有價值的方法。
"追加"意味著在不擦除當前可用資料的情況下將資料新增到檔案中。要追加檔案中的行,可以使用各種命令,例如printf、echo、tee、cat等。
雖然追加一行很容易,但許多初學者總是需要澄清。因此,本教程將包含向檔案追加不存在行的簡單方法。
檔案編輯:向檔案追加不存在的行
“>>”運算子可以重定向檔案的輸出。如果提到的檔案不存在,它會自動建立它,然後新增該行。使用此運算子,您可以使用多個命令向檔案新增新行。
您將藉助命令列印這些行,“>>”運算子將把此行列印到檔案中。例如,我們有一個名為“Linux.txt”的檔案,其中包含以下資訊:
:~$ cat Linux.txt What does append mean in Linux?
在這個檔案中,我們將使用幾個不同的命令追加新行。
printf命令
“printf”命令允許您編寫、格式化並將引數轉換為標準輸出。首先,我們將瞭解如何使用“>>”運算子和printf命令向檔案新增新行:
:~$ printf "<Text_line>
" >> <file_name>
現在讓我們使用以下命令在“Linux.txt”檔案中新增新行:
:~$ printf "You can append a line through various commands in the terminal.
" >> Linux.txt :~$ cat Linux.txt What does append mean in Linux? You can append a line through various commands in the terminal.
您可以看到,執行上述命令會在檔案中新增新的一行。
echo命令
使用內建的“echo”命令,您可以透過將其作為引數傳遞來顯示Linux中的文字字串/行。
:~$ echo "<new_text>" >> <file_name>
讓我們嘗試再次在Linux.txt中新增該行:
:~$ echo "You can append a line through various commands in the terminal.
" >> Linux.txt :~$ cat Linux.txt What does append mean in Linux? You can append a line through various commands in the terminal.
tee命令
Linux中的“tee”命令讀取輸入並將其列印到一個或多個檔案中。透過此命令,您可以將一個檔案的輸入列印到另一個檔案中。此外,您還可以使用tee命令直接在檔案中列印新行。
:~$ cat <source file_name> | tee -a <target file_name>
例如,我們將使用此命令將“Info.txt”檔案的內容列印到“Linux.txt”檔案中。這裡我們首先使用cat命令獲取“Info.txt”檔案中存在的行作為輸入。此外,我們將管道tee命令以將此輸入列印到“Linux.txt”檔案中。
:~$ cat Info.txt | tee -a Linux.txt You can append a line through various commands in the terminal. :~$ cat Linux.txt What does append mean in Linux? You can append a line through various commands in the terminal.
除此之外,您可以直接使用echo命令向檔案追加新行。同樣的方法是使用echo命令列印該行,然後將其與tee命令一起使用。
:~$ echo "<text_line>" | tee -a <file_name>
在上面的命令中,-a選項追加給定檔案的一行。讓我們將此命令組合應用於檔案:
:~$ echo "You can append a line through various commands in the terminal." | tee -a Linux.txt You can append a line through various commands in the terminal. :~$ cat Linux.txt What does append mean in Linux? You can append a line through various commands in the terminal.
cat命令
功能強大且通用的cat命令主要用於顯示檔案內容。除此之外,您還可以將內容從一個檔案列印到另一個檔案:
:~$ cat <source file_name> >> <target file_name>
這裡,我們將再次使用cat命令將“Linux1.txt”檔案的內容追加到“Linux.txt”檔案中。
:~$ cat Info.txt >> Linux.txt :~$ cat Linux.txt What does append mean in Linux? Append means simply add the data to the file erasing existing data.
結論
這是關於向檔案追加不存在行的簡單方法。我們解釋了四種在不修改現有輸出的情況下追加行的方法。請確保正確使用所有命令,因為不合適的命令有時會導致錯誤。此外,您可以訪問我們的官方網站了解更多關於Linux的資訊。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP