Append to an existing variable in a file

awksedtext processing

I have a Grub options file I want to modify via script. I want to add additional boot loader options.

The file might change over time, so I want to create something that adapts to future releases by appending to whatever boot loader options shipped with the image.

For example, the boot loader file contains the following:

# Set the recordfail timeout
GRUB_RECORDFAIL_TIMEOUT=0

# Do not wait on grub prompt
GRUB_TIMEOUT=0

# Set the default commandline
GRUB_CMDLINE_LINUX_DEFAULT="console=tty1 console=ttyS0"

# Set the grub console type
GRUB_TERMINAL=console
GRUB_HIDDEN_TIMEOUT=0.1

I want to append to the line GRUB_CMDLINE_LINUX_DEFAULT so that it ends up like:

GRUB_CMDLINE_LINUX_DEFAULT="console=tty1 console=ttyS0 cgroup_enable=memory swapaccount=1"

Is there a way I can do this with sed or awk? Something like "before the last quote of the line containing GRUB_CMDLINE_LINUX_DEFAULT append this."

Thanks in advance!

Best Answer

Simply with sed:

sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="[^"]*/& cgroup_enable=memory swapaccount=1/' file
  • [^"]* - match any character except double quote "
  • & - the whole matched string (pattern space)
Related Question