Day 54: Basic replaces with sed
One of the most powerful unix/linux command for parsing is sed.
The “find and replace” command has the following syntax:
sed 's/<before>/<after>' <file>
Find and replace:
$ cat foobar.txt
foobar
barfoo
$ sed 's/foobar/barfoo/' foobar.txt
barfoo
barfoo
Separator
The / separator is very popular on internet, but do you know that any char can be used as separator ?
$ sed 's#foobar#barfoo#' foobar.txt
barfoo
barfoo
$ sed 's?foobar?barfoo?' foobar.txt
barfoo
barfoo
Multiple occurencies
Just add g at the end of the sed command:
$ sed 's/bar/424242/' foobar.txt
foo424242
barfoo
$ sed 's/bar/424242/g' foobar.txt
foo424242
424242foo
Write changes on disk
This can be done with -i argument:
# override foobar.txt
$ sed -i 's/foobar/barfoo/' foobar.txt
$ cat foobar.txt
barfoo
barfoo
# override foobar.txt and backup previous file
$ sed -i.bak 's/foobar/barfoo/' foobar.txt
$ cat foobar.txt
barfoo
barfoo
$ cat foobar.txt.bak
foobar
barfoo
by ops for non-ops