LearneR
LearneR

Reputation: 2561

Search and replace one line with multiple lines in a unix script

I have the below script containing various commands, and I need to modify/replace one line with some new content and also add a comment above that says why the change was done.

Current script looks like below:

some random commands
some random commands
some random commands
some random commands
some random commands

OLM_VARIABLE=="-XYZ2048m ${OLM_VARIABLE} -XX:MaxBlahspaceSize=256m"

some random commands
some random commands
some random commands
some random commands
some random commands

The expected output is as follows:

Expected Output:

some random commands
some random commands
some random commands
some random commands
some random commands

##
# 2021-04-09 first comment line here
# 2021-04-09 second comment line here
##
OLM_VARIABLE="-XYZ2048m ${OLM_VARIABLE} -XX:MaxBlahspaceSize=512m -Dxyz.updateBlahConnectTimeout=10 -Dxyz.masterUpdateTimeInterval=123456"

some random commands
some random commands
some random commands
some random commands
some random commands

What I tried so far:

Method 1:

sed -i.bak $'s/OLM_VARIABLE=="-XYZ2048m ${OLM_VARIABLE} -XX:MaxBlahspaceSize=256m"/##\\\n#  2021-04-09 first comment line here \\\n# 2021-04-09 second comment line here \\\n##\\\nOLM_VARIABLE="-XYZ2048m ${OLM_VARIABLE} -XX:MaxBlahspaceSize=512m -Dxyz.updateBlahConnectTimeout=10 -Dxyz.masterUpdateTimeInterval=123456"/g'

Output:

sed: -e expression #1, char 104: unknown option to `s'

Method 2:

insert_this.txt:

##
# 2021-04-09 first comment line here
# 2021-04-09 second comment line here
##
OLM_VARIABLE="-XYZ2048m ${OLM_VARIABLE} -XX:MaxBlahspaceSize=512m -Dxyz.updateBlahConnectTimeout=10 -Dxyz.masterUpdateTimeInterval=123456"

I'm trying to use the above file insert_this.txt which holds the content that will be used for replacement:

awk '/OLM_VARIABLE=="-XYZ2048m ${OLM_VARIABLE} -XX:MaxBlahspaceSize=256m"/{system("cat insert_this.txt");next}1' file > file_new

Output: nothing happens. the original file stays as is

But neither of them are helpful in achieving what I want. Can someone please help me with this? Thanks in advance.

Upvotes: 2

Views: 49

Answers (1)

Ed Morton
Ed Morton

Reputation: 204731

$ awk 'NR==FNR{repl = (NR>1 ? repl ORS : "") $0; next} /^OLM_VARIABLE/{$0=repl} 1' insert_this.txt file
some random commands
some random commands
some random commands
some random commands
some random commands

##
# 2021-04-09 first comment line here
# 2021-04-09 second comment line here
##
OLM_VARIABLE="-XYZ2048m ${OLM_VARIABLE} -XX:MaxBlahspaceSize=512m -Dxyz.updateBlahConnectTimeout=10 -Dxyz.masterUpdateTimeInterval=123456"

some random commands
some random commands
some random commands
some random commands
some random commands

Upvotes: 1

Related Questions