如何使用命令行在文本文件的顶部插入一行?

Anw*_*war 29 command-line apt bash

我想在现有文件的顶部插入文本。我怎样才能做到这一点。我尝试过echotee但没有成功。

我试图在sources.list终端的文件顶部插入 repo 行。

笔记

我需要一个单行快速解决方案,因为我已经知道另一个答案的方法

ish*_*ish 43

这实际上很容易sed

  • sed -i -e '1iHere is my new top line\' filename

  • 1i告诉 sed 在文件的第 1 行插入后面的文本;不要忘记\末尾的换行符,以便将现有的第 1 行移动到第 2 行。

  • 遗憾的是,这对于空文件失败了(它没有第一行,所以 sed 从不插入)。 (4认同)

小智 8

在地方使用脚本编辑一般是棘手的,但你可以使用echocatmv

echo "fred" > fred.txt
cat fred.txt t.txt >new.t.txt
# now the file new.t.txt has a new line "fred" at the top of it
cat new.t.txt
# can now do the rename/move
mv new.t.txt t.txt
Run Code Online (Sandbox Code Playgroud)

但是,如果您正在使用 sources.list,您需要添加一些验证和防弹功能以检测错误等,因为您真的不想丢失它。但这是一个单独的问题:-)


Abd*_*UMI 6

./prepend.sh "myString" ./myfile.txt
Run Code Online (Sandbox Code Playgroud)

已知这prepend我的自定义外壳

#!/bin/sh
#add Line at the top of File
# @author Abdennour TOUMI
if [ -e $2 ]; then
    sed -i -e '1i$1\' $2
fi
Run Code Online (Sandbox Code Playgroud)

也使用相对路径或绝对路径,它应该可以正常工作:

./prepend.sh "my New Line at Top"  ../Documents/myfile.txt
Run Code Online (Sandbox Code Playgroud)

更新 :

如果你想要一个永久的脚本,打开nano /etc/bash.bashrc然后在文件末尾添加这个函数:

function prepend(){
# @author Abdennour TOUMI
if [ -e $2 ]; then
    sed -i -e '1i$1\' $2
fi

}
Run Code Online (Sandbox Code Playgroud)

重新打开您的终端并享受:

prepend "another line at top" /path/to/my/file.txt
Run Code Online (Sandbox Code Playgroud)


gni*_*urf 5

为什么不使用真正的文本编辑器呢?ed是标准的文本编辑器。

ed -s filename <<< $'1i\nFIRST LINE HERE\n.\nwq'
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望命令更具可读性:

ed -s filename < <(printf '%s\n' 1i "FIRST LINE" . wq)
Run Code Online (Sandbox Code Playgroud)
  • 1: 去第一线
  • i: 插入模式
  • 你要插入的东西...
  • .: 停止插入,回到正常模式
  • wq: 写完就退出了,谢谢,再见。