Anw*_*war 29 command-line apt bash
我想在现有文件的顶部插入文本。我怎样才能做到这一点。我尝试过echo
,tee
但没有成功。
我试图在sources.list
终端的文件顶部插入 repo 行。
我需要一个单行快速解决方案,因为我已经知道另一个答案的方法
ish*_*ish 43
这实际上很容易sed
:
sed -i -e '1iHere is my new top line\' filename
1i
告诉 sed 在文件的第 1 行插入后面的文本;不要忘记\
末尾的换行符,以便将现有的第 1 行移动到第 2 行。
小智 8
在地方使用脚本编辑一般是棘手的,但你可以使用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
Run Code Online (Sandbox Code Playgroud)
但是,如果您正在使用 sources.list,您需要添加一些验证和防弹功能以检测错误等,因为您真的不想丢失它。但这是一个单独的问题:-)
./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)
为什么不使用真正的文本编辑器呢?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
: 写完就退出了,谢谢,再见。 归档时间: |
|
查看次数: |
78878 次 |
最近记录: |