如何使用命令行在文本文件的顶部插入一行?
我想在现有文件的顶部插入文本。 我怎样才能做到这一点。 我试过echo
和tee
但是没有成功。
我试图在终端的sources.list
文件的顶部插入repo行。
注意
我需要一个单行快速解决方案,因为我已经知道另一个答案的方法
用sed
实际上很容易:
-
sed -i -e '1iHere is my new top line\' filename
-
1i
告诉sed在文件的第1行插入后面的文本; 不要忘记末尾的\
换行符,以便将现有的第1行移动到第2行。
通常使用脚本进行编辑很棘手,但您可以使用echo
和cat
然后使用mv
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
但是,如果你正在使用sources.list,你需要添加一些validation和防弹以检测错误等,因为你真的不想放松它。 但这是一个单独的问题:-)
./prepend.sh "myString" ./myfile.txt
已知prepend
是我的自定义shell :
#!/bin/sh #add Line at the top of File # @author Abdennour TOUMI if [ -e $2 ]; then sed -i -e '1i$1\' $2 fi
使用相对路径或绝对路径,它应该工作正常:
./prepend.sh "my New Line at Top" ../Documents/myfile.txt
更新:
如果你想要一个永久性脚本,打开nano /etc/bash.bashrc
然后在文件末尾添加这个函数:
function prepend(){ # @author Abdennour TOUMI if [ -e $2 ]; then sed -i -e '1i$1\' $2 fi }
重新打开终端并享受:
prepend "another line at top" /path/to/my/file.txt
为什么不使用真正的文本编辑器呢? ed是标准文本编辑器。
ed -s filename <<< $'1i\nFIRST LINE HERE\n.\nwq'
或者,如果您希望命令更具可读性:
ed -s filename < <(printf '%s\n' 1i "FIRST LINE" . wq)
-
1
:转到第一线 -
i
:插入模式 - 你要插入的东西......
-
.
:停止插入,返回正常模式 -
wq
:写,退出,谢谢,再见。
总有awk
选项。 用您的内容替换string
变量。 这不是一个就地改变。 就个人而言,我倾向于不进行就地更改。 这绝对是个人喜好。 两个方面, -v
表示awk中的变量,变量n
用于匹配行号,实际上NR == 1
。 您可以通过更改n
和s
的值以多种方式使用它。
string="My New first line"; awk -vn=1 -vs="$string" 'NR == n {print s} {print}' file.source > file.target
例:
% cat file.source First Line Second Line Third Line % string="Updated First Line"; awk -vn=1 -vs="$string" 'NR == n {print s} {print}' file.source > file.target; cat ./file.target !698 Updated First Line First Line Second Line Third Line
您可以在Ex模式下使用Vim:
ex -sc '1i|hello world' -cx sources.list
-
1
选择第一行 -
i
插入新的文字行 -
x
保存并关闭