在文件中查找唯一的字符串,向上一行并追加? [英] Find unique string within a file, up a line and append?

查看:92
本文介绍了在文件中查找唯一的字符串,向上一行并追加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以在这种情况下帮助我吗?我正在寻找SED或AWK命令,可用于在配置文件(Linux)中查找唯一的字符串,上一行并将一个字符串附加到该行的末尾?

Can someone please help me with this scenario? I'm looking for a SED or AWK command that I can use to find a unique string within a config file (Linux), go up a line and append a string to the end of that line?

例如:

配置文件:

定义主机组{
hostgroup_name http-urls;主机组的名称
别名HTTP URL;组的长名称
成员domain1.com,domain2.com,domain3.com,
#MyUniqueString
}

define hostgroup{
hostgroup_name http-urls ; The name of the hostgroup
alias HTTP URLs ; Long name of the group
members domain1.com, domain2.com, domain3.com,
#MyUniqueString
}

在上面的示例中,我想使用SED或AWK查找 #MyUniqeString ,在以 members 开头的行上附加"行末.

In the above example, I'd like to use SED or AWK to find #MyUniqeString, go up a line that starts with members and append "domain4.com" at the end of the line.

我在下面找到了这个问题,但我需要先在文本文件中搜索字符串,然后在上面一行.

I found this question below but I need to search the text file first for the string, and go one line above.

Bash脚本:在文件特定行的最后一个字符后附加文本

有什么建议吗?

推荐答案

尝试以下一种方法:

awk '{a[NR]=$0}/#MyUniqueString/{a[NR-1]=a[NR-1]"domain4.com"}END{for(i=1;i<=NR;i++)print a[i]}' configFile

测试

kent$  cat test.txt 
define hostgroup{
hostgroup_name http-urls ; The name of the hostgroup
alias HTTP URLs ; Long name of the group
members domain1.com, domain2.com, domain3.com,
#MyUniqueString
}

kent$  awk '{a[NR]=$0}/#MyUniqueString/{a[NR-1]=a[NR-1]"domain4.com"}END{for(i=1;i<=NR;i++)print a[i]}' test.txt 
define hostgroup{
hostgroup_name http-urls ; The name of the hostgroup
alias HTTP URLs ; Long name of the group
members domain1.com, domain2.com, domain3.com,domain4.com
#MyUniqueString
}

这篇关于在文件中查找唯一的字符串,向上一行并追加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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