Home > front end >  Use sed to replace pattern and insert variable on the inserted string
Use sed to replace pattern and insert variable on the inserted string

Time:09-13

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"

CodePudding user response:

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"

CodePudding user response:

Another alternative, if you're interested...

Put each of your parameters for GRUB_CMDLINE_LINUX into a file, with one on each line. Whenever you get a new one, just add it to either the top or bottom line, as you choose.

hugepages=53737
processor.max_cstates=1
idle=poll
pcie_aspm=off
intel_iommu=on

Then when you're ready to add all of them to the variable...

cat parameter_file | tr '\n' ' ' > p2
cat << EOF > ed1
1
s/^/GRUB_CMDLINE_LINUX="/
s/$/"/
1W grub.text
wq
EOF

ed -s p2 < ed1
rm -v ./ed1

That will put your variable at the end of the file, but from there, you can use either Ed or vim to move it to whichever line you need.

  • Related