1

I'm trying to do a replacement inline in a configuration file after defore deploying this file. I looked in the sed documentation but I can't get it working. Even with -e For now I mv into .back file and then sed to the file, finishing by rm the file. I'm sure there's an easier way to do that but can't get it working.

Thanks

mv file.conf file.back sed s/string/anotherstring/ file.back > file.conf rm file.back

2
  • 3
    "but I can't get it working" you're going to need to describe which bit fails, and why. Aug 28, 2013 at 12:50
  • 1
    +1 @EightBitTony, and you should also take the time to reformat your question to be more readable.
    – Luke404
    Aug 28, 2013 at 13:18

1 Answer 1

6

If you need to modify files content instantly you can use the sed -e 's/your/expression/g' -i filename. You can add a -i.bak to backup the original file before any change happens.

Adding, that sed is a Stream EDitor and you rather should use ed or ex.

Update example:

[val0x00ff@localhost dir1]$ ls
file
[val0x00ff@localhost dir1]$ cat file 
test
anothertest
hangethisLine/g

[val0x00ff@localhost dir1]$ sed -i.bak 's/test/substitute_to_this/g' file 
[val0x00ff@localhost dir1]$ ls -l
total 8
-rw-rw-r-- 1 val0x00ff val0x00ff 62 Aug 28 14:59 file
-rw-rw-r-- 1 val0x00ff val0x00ff 34 Aug 28 14:58 file.bak
[val0x00ff@localhost dir1]$ cat file
substitute_to_this
anothersubstitute_to_this
hangethisLine/g

[val0x00ff@localhost dir1]$ cat file.bak 
test
anothertest
hangethisLine/g

See how -i.bak creates a backup file automatically to protect us from overriding the file by accident.

See lin http://wiki.bash-hackers.org/howto/edit-ed for examples using the ed editor.

7
  • 1
    what's the difference with sed 's/your/expression/g' -i filename ?
    – mveroone
    Aug 28, 2013 at 12:56
  • 1
    There is very little difference with one sed expression (man page says -e "add the script to the commands to be executed") but if you want to use more than one you need -e for each sed command in the command line.
    – adric
    Aug 28, 2013 at 13:13
  • @Kwaio There is no difference. -i.back can be placed either in the beginning of the sed expression as well as just before the filename. Aug 28, 2013 at 15:34
  • I'm also intrested in the effect of the omission of the 's' in front of the replacement pattern.
    – mveroone
    Aug 29, 2013 at 8:29
  • 1
    So there is really a 's' missing at the first line of this answer. I didn't want to state it until you confirm but I guessed well.
    – mveroone
    Aug 29, 2013 at 8:54

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