Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use sed to replace pattern and insert variable on the inserted string

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=*.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading