Issue
In my script, I have the following variable already defined: GRUB_HG=53737
I am trying to replace the contents of this file:
cat grub.text
{...}
GRUB_CMDLINE_LINUX="random_text_here"
I am using sed
to replace anything that starts with GRUB_CMDLINE_LINUX=*.
When I used the following sed
script, I am replacing the "random_text_here" with a long string. This string contains the variable $GRUB_HG, however, when I run the script I am able to replace the "random_text_here" successfully, but the $GRUB_HG is not getting replaced with 53737 which was previously defined.
Script:
sed -i 's|\GRUB_CMDLINE_LINUX=.*|GRUB_CMDLINE_LINUX="hugepages=${GRUB_HG} processor.max_cstates=1 idle=poll pcie_aspm=off intel_iommu=on"|' grub.text
This is what the file grub.text looks like after the sed
command:
#[ACTUAL OUTPUT]
cat grub.text
{...}
GRUB_CMDLINE_LINUX="hugepages=${GRUB_HG} processor.max_cstates=1 idle=poll pcie_aspm=off intel_iommu=on"
I am trying to get something like this:
#[DESIRE OUTPUT]
cat grub.text
{...}
GRUB_CMDLINE_LINUX="hugepages=53737 processor.max_cstates=1 idle=poll pcie_aspm=off intel_iommu=on"
Solution
You need to use double quotes in order for the bash variable to be interpolated in the sed
command. As you have double quotes in your replacement string you need to escape those:
cat grub.text
GRUB_CMDLINE_LINUX="random_text_here"
GRUB_HG=53737 sed -i "s|\GRUB_CMDLINE_LINUX=.*|GRUB_CMDLINE_LINUX=\"hugepages=${GRUB_HG} processor.max_cstates=1 idle=poll pcie_aspm=off intel_iommu=on\"|" grub.text
cat grub.text
GRUB_CMDLINE_LINUX="hugepages=53737 processor.max_cstates=1 idle=poll pcie_aspm=off intel_iommu=on"
Answered By - htaccess Answer Checked By - David Marino (WPSolving Volunteer)