我如何一行文本添加到使用bash文件的中间? [英] How do I add a line of text to the middle of a file using bash?
问题描述
我试图一行文本添加到一个bash脚本的文本文件的中间。特别是我想一个域名服务器添加到我的/etc/resolv.conf文件。因为它的立场,resolv.conf的是这样的:
I'm trying to add a line of text to the middle of a text file in a bash script. Specifically I'm trying add a nameserver to my /etc/resolv.conf file. As it stands, resolv.conf looks like this:
# Generated by NetworkManager
domain dhcp.example.com
search dhcp.example.com
nameserver 10.0.0.1
nameserver 10.0.0.2
nameserver 10.0.0.3
我的目标是添加域名服务器127.0.0.1
所有其他名称服务器线上方,但低于上述的任何文字。最后,我想我的resolve.conf文件看起来是这样的:
My goal is to add nameserver 127.0.0.1
above all other nameserver lines, but below any text above that. In the end I want to my resolve.conf file to look like this:
# Generated by NetworkManager
domain dhcp.example.com
search dhcp.example.com
nameserver 127.0.0.1
nameserver 10.0.0.1
nameserver 10.0.0.2
nameserver 10.0.0.3
如何通过bash脚本,这可能吗?这是不是awk或者sed可以做什么?或将创意greping重新创建该文件是我最好的举动?
How is this possible via a bash script? Is this something sed or awk can do? Or would creative greping to recreate the file be my best move?
推荐答案
下面是一个使用SED的解决方案:
Here is a solution using sed:
$ sed -n 'H;${x;s/nameserver .*\n/nameserver 127.0.0.1\
&/;p;}' resolv.conf
# Generated by NetworkManager
domain dhcp.example.com
search dhcp.example.com
nameserver 127.0.0.1
nameserver 10.0.0.1
nameserver 10.0.0.2
nameserver 10.0.0.3
它是如何工作的:第一,SUP preSS与 -n
标记的sed的输出。然后,对于每个行,我们追加行保留空间,他们用换行分隔:
How it works: first, suppress the output of sed with the -n
flag. Then, for each line, we append the line to the hold space, separating them with newlines:
H
当我们来到文件( $
处理)结束时,我们移动保持空间模式空间的内容:
When we come to the end of the file (addressed by $
) we move the content of the hold space to the pattern space:
x
然后我们替换第一行含有域名服务器127.0.0.1
A线,新的生产线与域名服务器
启动(重新由 psented \\
$ p $跟着一个换行符 - 也许你的sed版本支持 \\ n
,而不是... )和原线(通过重新psented $ p $ &安培;
)
Then we replace the first line starting with nameserver
by a line containing nameserver 127.0.0.1
, a new line (represented by \
followed by a newline - maybe your sed version supports \n
instead...) and the original line (represented by &
):
s/nameserver .*\n/nameserver 127.0.0.1\
&/
现在,我们只需要打印结果:
Now we just need to print the results:
p
这篇关于我如何一行文本添加到使用bash文件的中间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!