如何在 Linux 系统中向文件开头插入文本?
linuxoperating systemopen source
要在文本文件的开头插入文本,我们需要熟悉 sed 命令,因为 sed 命令可以用来解决上述问题。
我们先来了解一下 sed 命令,它是 stream editor(流编辑器)的缩写。该命令用于对特定文件执行查找、替换、插入等各种操作。
假设我们有一个目录 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
相关文章
有用资源
linux 参考教程 - 该教程包含有关 linux 的更多信息:https://www.cainiaomax.com/linux/

