I feel dumb as a sack of hammers asking this here, but it's been a long day and I simply CANNOT figure out what I'm doing wrong here.
I have a file; we'll call it textfile.txt
. It's contents are (in this representative, but contrived example) as follows:
FILE CONTENTS
SOME=1
TRIED="THEIR BEST AT"
INSERTING='A VALUE'
BE=4
Now, assume I have two variables $KEY
and $VAL
, representing, oh, we'll say the key and value I want to update in the file
(Brief aside: I CAN guarantee that neither will ever contain a quote ["] or apostrophe [']):
NEW VALUES
KEY="TRIED"
VAL="THEIR HAND AT"
Okay, great. So now I fire off what seems like it should be a bog-standard regex replace (note that I'm attempting to keep the replaced value enclosed in whatever optional delimiters it has encircling it presently):
sed -E "s/$KEY=([\"']?).*([\"']?)/$KEY=\1$VAL\2/g" textfile.txt > textfile.txt
EXPECTED RESULT
SOME=1
TRIED="THEIR HAND AT"
INSERTING='A VALUE'
BE=4
ACTUAL RESULT
(an empty file)
Okay, fine, so how about I target a NEW file instead of the one I'm reading from?
sed -E "s/$KEY=([\"']?).*([\"']?)/$KEY=\1$VAL\2/g" textfile.txt > textfile2.txt
NEW RESULT
SOME=1
TRIED="THEIR HAND AT
INSERTING='A VALUE'
BE=4
Capital!
...except now JUST the second delimiter (the double-quote trailing AT
) is missing around the value. I can re-use \1
, which works, but I feel this is brittle enough without figuring out where I'm dropping the ball here.
So... Question:
- Why does my first attempt purge the file outright?
- Why does my second omit the latter delimiter?
Note that I'm totally not married to this approach, and am fine with going another route, but if someone could PLEASE explain those two points AS WELL, I'd be much obliged. I woulda sworn up and down I knew RegEx if you'd asked me yesterday, but it's been a minute since I've used it in Shell.
I'm running GNU bash, version 5.2.12 on a 2021 MacBook M Chip Pro on Ventura 13.0 if that helps.
sed (GNU sed) 4.8
– Gilles Quénot Dec 05 '22 at 22:49cat textfile2.txt
you get both? Oh, gods, now I'm REALLY baffled. – NerdyDeeds Dec 05 '22 at 22:51dos2unix
. No luck. Great suggestion, though! Didn't even occur to me. – NerdyDeeds Dec 05 '22 at 22:59cat
it out then pipe it into the write? – NerdyDeeds Dec 05 '22 at 23:03sed
supports-i
here's the way to do it https://unix.stackexchange.com/a/505600 – don_crissti Dec 05 '22 at 23:05