Issue
here is short sed example how to replace the value after "=
" separator
sed -i "/num.replica.fetchers/s/=.*$/=$num_cpu/" kafka.configuration
and this above sed example is relevant when the following key and val - num.replica.fetchers = XX
exist in file as example
#section A
num.replica.fetchers = 12
but in case "num.replica.fetchers = 12
" not exist in file then sed will do nothing
so I just wondering if we can improve the sed in order to add the key and value "num.replica.fetchers = 12
" after matched line "#section A
" in case key not exist in file
so is it possible to improve my sed in order to support also the condition when key not exist and in this case just add the num.replica.fetchers = 12
after matched line - #section A
Solution
Yes you can (I've not tested the below code):
# ensure #section A exists in the file:
if ! grep -q '^#section A' kafka.configuration; then
echo '#section A' >> kafka.configuration
fi
# then append to it (next line) your config line:
num_cpu=32
if grep -q '^num.replica.fetchers' kafka.configuration; then
sed -i "/num.replica.fetchers/s/=.*$/= $num_cpu/g" kafka.configuration
else
sed -i "/#section A/a num.replica.fetchers = $num_cpu" kafka.configuration
fi
You can also play with grep to check if there's a match specifically after #section A
(in the next few lines)
Answered By - Ron Answer Checked By - Candace Johnson (WPSolving Volunteer)