如何在 Linux 中在檔案開頭插入文字?
為了在文字檔案的開頭插入文字,我們必須熟悉 **sed** 命令,因為 sed 命令可以用來解決上述問題。
讓我們首先探索 **sed 命令**,它是流編輯器的縮寫。此命令用於對特定檔案執行不同的功能,例如查詢、替換、插入等等。
假設我們有一個名為 **d1** 的目錄,其中存在兩個 **.txt** 檔案,目錄結構如下所示:
immukul@192 d1 % ls -ltr total 8280 -rwxrwxrwx 1 immukul staff 4234901 Jul 7 17:41 file.txt -rw-r--r-- 1 immukul staff 105 Jul 16 09:30 somefile.txt
現在我們想更改名為 **somefile.txt** 檔案的內容,並在 .txt 檔案的第一行插入一些我們選擇的文字。
在向檔案插入任何內容之前,somefile.txt 的內容如下所示
immukul@192 d1 % cat somefile.txt this file contains a new text stream and i am going to edit that stream yes i can do that ask jeffrey
現在,為了在第一行新增一些文字,我們將使用下面顯示的命令
命令
適用於 Mac OS
sed -i "" '1s/^/Is this text added
/' somefile.txt
適用於 Ubuntu/Fedora
sed -i '1s/^/Is this text added
/' somefile.txt
輸出
immukul@192 d1 % cat somefile.txt Is this text added this file contains a new text stream and i am going to edit that stream yes i can do that ask jeffrey
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP