Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find unique string within a file, up a line and append?

Tags:

linux

bash

sed

awk

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?

For example:

config file:

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
}

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 script: Appending text at the last character of specific line of a file

Any suggestions?

like image 450
Mike J Avatar asked Dec 26 '22 12:12

Mike J


2 Answers

here's another sed solution using backreferences:

sed '{N; N; s/\(.*\)\n\(#MyUniqueString\)/\1domain4.com\n\2/g}' config.file
like image 28
nullrevolution Avatar answered Dec 31 '22 12:12

nullrevolution


You can do this effectively with ed:

ed yourfile <<-'EOF'
    /#MyUniqueString/ # Find the matching line
    - # Go up a line
    a # Append text
    domain4.com
    . # Stop appending
    .-1,.j # Join the line above with the appended line
    w # Write the line
EOF
like image 115
kojiro Avatar answered Dec 31 '22 14:12

kojiro