3

I'm wanting to make a command to edit /etc/default/grub and change the timeout from 10 to 2. Could anyone explain how to do this?

2 Answers 2

6

You can use sed, perl and other tools for that. Here are two examples for sed and perl:


Using sed:

Start a dry run

sudo sed 's/^GRUB_TIMEOUT=10$/GRUB_TIMEOUT=2/' /etc/default/grub

if it's ok, then

sudo sed -i 's/^GRUB_TIMEOUT=10$/GRUB_TIMEOUT=2/' /etc/default/grub

from man sed:

   -i[SUFFIX], --in-place[=SUFFIX]

          edit files in place (makes backup if SUFFIX supplied)

Explanation:

  • ^GRUB_TIMEOUT=10$

    Regular expression visualization
    (source: debuggex.com)

    Debuggex Demo

    ^ - assert position at start of the string

    GRUB_TIMEOUT=10 matches the characters GRUB_TIMEOUT=10 literally (case sensitive)

    $ - assert position at end of the string

  • s - s-modifier: single line


Using perl and more generic:

Start a dry run

perl -pe 's/^(GRUB_TIMEOUT=)[0-9]+$/${1}2/' /etc/default/grub

if it's ok, then

sudo perl -pi -e 's/^(GRUB_TIMEOUT=)[0-9]+$/${1}2/' /etc/default/grub
3
  • So let's say I needed to change ssh=22 > ssh=2020 I would use 's/^(ssh=)[0-9]+/{22}2020/g' Apr 30, 2015 at 20:16
  • 1
    With perl or sed?
    – A.B.
    Apr 30, 2015 at 20:23
  • perl -pe 's/^(ssh=)[0-9]+$/${1}2020/g' input_file
    – A.B.
    Apr 30, 2015 at 20:37
1

Here is a generic one:

sudo sed -i.bak 's/^\(GRUB_TIMEOUT=\)[0-9]\+$/\12/' /etc/default/grub

Replace 2 (after \1) with any value you want to put.

  • s/OLD/NEW/ is the substitution pattern for sed.

  • i.bak will edit the file /etc/default/grub in place, keeping the original file backed up as /etc/default.grub.bak. If you don't want a backup just use -i.

  • We have matched the line that starts with GRUB_TIMEOUT= (Kept it inside a group so that we can refer to it later) and ends with one or more digits ([0-9]+).

  • In the replacement section we replaced the digits with the value we want to put, keeping the earlier matched portion (denoted by \1) as it is.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .