This is a bit of a follow-on from How to use sed to replace only the first occurrence in a file? but with a more targeted ask. Given a file
Peach: data/file1.txt
Apple: data/file2.txt
Pear: data/file3.txt
Apple: data/file4.txt
The goal is to replace only the first line containing Apple with a new line containing a fixed string (Banana) followed by a bash variable. In the new output, line 2 is now:
Banana: newdata/data.txt
Here is the most recent attempt...
BananaVariable=newdata
sed -i -E "0,|(Apple).*|{s|(Apple:).*|Banana: "$BananaVariable"/data.txt|}" filename
However, this produces the error:
sed: -e expression #1, char 3: unexpected `,'
I think I need the double quotes around $BananaVariable to escape so that it can insert the actual string rather than "BananaVariable", but I think those double quotes are causing the problem. (OS is CentOS 7, sed is GNU version)