44

I'm building a bash script for my virtual machine and I would like to know how to replace a specific line in this document:

[base]

## uncomment and set autologin username to enable autologin
# autologin=dgod

## uncomment and set timeout to enable timeout autologin,

## the value should >=5

# timeout=10

## default session or desktop used when no systemwide config

# session=/usr/bin/startlxde

this line:

# autologin=dgod

I want to change to this

autologin=ubuntu

I have tried with "tee" and "sed" but couldn't make it work. This should be very easy for someone who works with bash scripts more often than me.

1
  • 3
    sed -i 's/^# autologin=.*/autologin=ubuntu/' /some/file?
    – muru
    Oct 15, 2016 at 8:48

2 Answers 2

59

It is straightforward. Use the s command in sed to search and replace.

sed 's/# autologin=dgod/autologin=ubuntu/' /path/to/file

If you see what you want, add -i to change the file in place

sed -i 's/# autologin=dgod/autologin=ubuntu/' /path/to/file
6
  • the filename is /etc/lxdm/default.conf - so the full command should be like this? = sed -i 's/# autologin=dgod/autologin=ubuntu/' /etc/lxdm/default.conf
    – lewis4u
    Oct 15, 2016 at 8:51
  • yes, exactly like that @lewis4u
    – Zanna
    Oct 15, 2016 at 8:52
  • No /g at the end? Aug 30, 2021 at 14:40
  • @Tjorriemorrie g means apply the command to every occurrence on the line specified, which is not relevant to this case
    – Zanna
    Aug 30, 2021 at 15:26
  • 1
    @Gulzar yes, you need a final / before your closing quote, i.e. sed 's/# 1/1/' /etc/gai.conf
    – Zanna
    Jan 20, 2022 at 17:26
5

I've found the most effective way to do this is actually to use the change syntax to set the exact value you want unless you are explicitly trying to enable a two way toggle. You can use this to change as well as uncomment a line no matter how it is commented, with # or // or <!--.

sed 's%searchTerm=% c searchTerm=desiredValue%' targetFile.txt

1
  • You could mention that % is used to replace the / delimiter. Got me questioning my sanity for a while...
    – Sherlock70
    Mar 30, 2023 at 14:19

You must log in to answer this question.

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