如何在 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

更新於: 2021-07-30

3K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.