Skip to main content

Find and replace with sed command in Linux

Find and replace feature is always handy. It can turn into a torture when it comes to change or delete a simple constant string in a text file. There is a handy tool in linux for doing these kind of tihngs. Actually sed is not a text editor but it is used outside of the text file to make changes.

How sed works?
Sed tool reads given text file line by line, does the defined operation then displays the results unless you give a target text file. We can clarify with some examples.

The syntax of the sed command is like: sed [options] '{command}' [file name]

Substitute 
's/{old value}/{new value}/'
$ echo could you smile a little smile for me | sed 's/little/big/'
$ could you smile a big smile for me
little is replaced by big.

Multiple change
it is used with -e option.
$ echo could you smile a little smile for me | sed -e 's/little/big/' -e 's/smile/laugh/'
$ could you laugh a big smile for me
In this example we can use ; rather than -e they are same.
$ echo could you smile a little smile for me | sed -e 's/little/big/; s/smile/laugh/'
$ could you laugh a big smile for me
Attention that the second smile remained same. To change all occurences, g option must be used.

Global changes
g option must be used.
$ echo could you smile a little smile for me | sed 's/smile/laugh/g'
$ could you laugh a little laugh for me

Some examples with text files
$ cat sed.txt
ankara 00
istanbul 00
izmir 00
ankara 00
izmir 00
istanbul 00

$ sed '/ankara/ s/00/06/' sed.txt
ankara 06
istanbul 00
izmir 00
ankara 06
izmir 00
istanbul 00

$ sed '/ankara/ s/00/06/; /istanbul/ s/00/34/; /izmir/ s/00/35/' sed.txt
ankara 06
istanbul 34
izmir 35
ankara 06
izmir 35
istanbul 34

change second and third lines.
$ sed '2,3 s/00/99/' sed.txt
ankara 00
istanbul 99
izmir 99
ankara 00
izmir 00
istanbul 00

delete lines contains izmir.
$ sed '/izmir/ d' sed.txt
ankara 00
istanbul 00
ankara 00
istanbul 00

write the changed text to another file.
$ sed '/ankara/ s/00/06/; /istanbul/ s/00/34/; /izmir/ s/00/35/' sed.txt > sednew.txt

Comments

Popular posts from this blog