51

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.

Zanna
  • 72,312
lewis4u
  • 5,046

2 Answers2

68

You can use the s command to search and replace.

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

Explanation

  • s - The substitute command. The syntax is s/regexp/replacement/flags.
  • # autologin=dgod - Look for "# autologin=dgod"
  • autologin=ubuntu - Change it to "autologin=ubuntu"
  • There are no flags in this command, so it ends with /

This command sends the modified text to stdout (the command line) without modifying the source file. If the output is what you want, add -i to change the file in place:

sed -i 's/# autologin=dgod/autologin=ubuntu/' /path/to/file
Zanna
  • 72,312
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

dragon788
  • 1,716