如何使用 bash 在文件中间添加一行文本? [英] How do I add a line of text to the middle of a file using bash?

查看:35
本文介绍了如何使用 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

我的目标是在所有其他名称服务器行上方添加 nameserver 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 脚本实现?这是 sed 或 awk 可以做的吗?或者创造性地重新创建文件是我最好的举动吗?

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/^
//;s/nameserver .*$/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

它是如何工作的:首先,使用 -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

如果模式空间中的第一行是空白的,我们将其替换为空.

If the first line in pattern space is blank we replace it with nothing.

s/^
//

然后我们用包含 nameserver 127.0.0.1 的行替换以 nameserver 开头的第一行,新行(您的 sed 版本)可能不支持 ,在这种情况下,将 n 替换为文字换行符)和原始行(由 & 表示):

Then we replace the first line starting with nameserver by a line containing nameserver 127.0.0.1, a new line (Your version of sed may not support , in which case replace the n with a literal newline) and the original line (represented by &):

s/nameserver .*$/nameserver 127.0.0.1
&/

现在我们只需要打印结果:

Now we just need to print the results:

p

这篇关于如何使用 bash 在文件中间添加一行文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆