有人可以帮我解决这个问题吗?我正在寻找一个SED或AWK命令,我可以用它在配置文件(
Linux)中找到一个唯一的字符串,上一行并在该行的末尾添加一个字符串?
例如:
配置文件:
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,上一行以成员开头,并在行尾添加“domain4.com”.
我在下面发现了这个问题,但我需要首先搜索文本文件中的字符串,然后在上面找一行.
Bash script: Appending text at the last character of specific line of a file
有什么建议?
解决方法
试试这个单行:
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,#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,domain4.com #MyUniqueString }