Colonel Mustard
Colonel Mustard

Reputation: 1533

Bash replace lines in file that contain functions

I have a shell script that contains the following line

PROC_ID=$(cat myfile.sh | grep running)

which, after you echo out the value would be 1234 or something like that.

What I want to do is find and replace instances of this line with a literal value

I want to replace it with PROC_ID=1234 instead of having the function call.

I've tried doing this in another shell script using sed but I can't get it to work

STR_TO_USE="PROC_ID=${1}"
STR_TO_REP='PROC_ID=$(cat myfile.sh | grep running)'

sed -i "s/$STR_TO_REP/$STR_TO_USE/g" sample.sh

but it complains stating sed: 1: "sample.sh": unterminated substitute pattern

How can I achieve this?

EDIT: sample.sh should contain beforehand

#!/bin/bash
....

PROC_ID=$(cat myfile.sh | grep running)
echo $PROC_ID

....

After, it should contain

#!/bin/bash
....

PROC_ID=1234
echo $PROC_ID

....

The script I'm using as described above will be taking the in an arg from the command line, hence STR_TO_USE="PROC_ID=${1}"

Upvotes: 1

Views: 52

Answers (2)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 70882

Simply:

sed /^PROC_ID=/s/=.*/=1234/

Translation:

  • At line begining by PROC_ID=
  • replace = to end of line by =1234.

or more accurate

sed '/^[ \o11]*PROC_ID=.*myfile.*running/s/=.*/=1234/'

could be enough

  • ([ \o11]* mean some spaces and or tabs could even prepand)

Upvotes: 2

user3546408
user3546408

Reputation:

Well, first, I want to point out something obvious. This: $(cat myfile.sh | grep running) will at the very least NOT only contain the string 1234 but will certainly also contain the string running. But since you aren't asking for help with that, I'll leave it alone.

All you need in your above sed, is first to backslash the $.

STR_TO_REP='PROC_ID=\$(cat myfile.sh | grep running)'

This allows the sed command to be terminated.

Upvotes: 0

Related Questions