So my question is very much based off of a related question, but has one key difference.
In the answer given of:
sed '/^FOOBAR=/{h;s/=.*/=newvalue/};${x;/^$/{s//FOOBAR=newvalue/;H};x}' infile
I've made a variation that works for making FOOBAR
a variable (e.g. name of a program and then putting it in a for loop to make a list of programs and their installation status). This is for a rather involved project I'm working on to make the installation of Drawile for Raspberry Pi easy with some new features, but that's a different can of worms I'm not going to get into.
sed -i '/^'"$FOOBAR"'=/{h;s/=.*/=newvalue/};${x;/^$/{s//'"FOOBAR"'=newvalue/;H};x}' infile
I would like newvalue
to be a $variable
which can change in the script. I just can't figure out how to make that work, simply using '
and "
doesn't do it right. I've spent hours browsing and trying to read tutorials, but I just don't understand enough and have dived very deep into the inner workings of sed. Most of the time, this variable will be something simple like: yes
, no
, or error
. However, I might also use it to represent folder and file paths... so I'm worried about /
substitutions as well here. Even if it's not a full answer, I'm happy to figure it out myself as long as I can get pointed in the direction that I need to go to understand this better.
Edit: There isn't much to post given that there's something fundamental I'm sure I'm missing, I've just tried variations of putting quotes around newvalue. Such as follows...
sed -i '/^FOOBAR=/{h;s/=.*/=$newvalue/};${x;/^$/{s//FOOBAR=$newvalue/;H};x}' infile
Output: FOOBAR = $newvalue
This is incorrect. Should output the stored value for newvalue
!
sed -i '/^FOOBAR=/{h;s/=.*/="$newvalue"/};${x;/^$/{s//FOOBAR="$newvalue"/;H};x}' infile
Output: FOOBAR = "$newvalue"
This is incorrect. Should output the stored value for newvalue
!
sed -i '/^FOOBAR=/{h;s/=.*/='"$newvalue"'/};${x;/^$/{s//FOOBAR='"$newvalue"'/;H};x}' infile
Output: sed: -e expression #1, char 30: unknown option to `s'
If newvalue
is equal to Yes
, then I'd want the output to be FOOBAR = Yes
or possibly a folder path.
sed
? It'd be much easier with e.g. perl or awk, or even carefully combined shell builtins.'"$newvalue"'
should work, I think, unless$newvalue
alterssed
logic. If e.g. it contains/
then choose another character as delimiter forsed
.sed 's/a/b/'
can besed 's|a|b|'
or evensed 'sRaRbR'
. Choose a character that doesn't collide with possible$newvalue
.unknown option to 's'
. Try it with$newvalue
that doesn't contain/
.\$
) the end of line/last line references:sed "/^$FOOBAR=/{h;s/=.*/=$newvalue/};\${x;/^\$/{s//$FOOBAR=$newvalue/;H};x}"
. But bear in mind @KamilMaciorowski's comment on/
in$newvalue
, which means that you may need to change the delimiter.sed \|^FOOBAR=|...etc
. Ins
command escape isn't needed.