search and replace

November 1st, 2006 mysurface Posted in Misc, sed, sudo, Text Manipulation, vi, vim | Hits: 61877 | 3 Comments »

This is a very common needs, to search a keyword and replace it with another. Give you a simple example, when I want to perform a ubuntu distribution upgrade from dapper to edgy, I need to edit the file /etc/apt/sources.list.

To do that i can either uses vim, or simply uses sed.

The vim way.

sudo vim /etc/apt/source.list

When in vim, you can do this


%s ask vim to search for every line, and replace dapper to edgy. By default, it will only replace the first “dapper” it found in a line, the /g will indicate it replace all “dapper” in a line.

The sed way.

sudo sed -e 's/dapper/edgy/g' -i /etc/apt/sources.list

-e is the script function, it performs search and replace like vi, and -i is the edit the file in place.

3 Responses to “search and replace”

  1. there is still have another way – called perl way :p

    sudo perl -pi -e ‘s/dapper/edgy/g;’ xyz

  2. […] You can execute the vim command, while opening files with vim with option -c. While I wanna replace a string from a huge file, first I need to check whether I can do it with sed or not. That means my replace string must be unique, so that it won’t affect others line thatI might not want to replace. […]

  3. sudo sed -e ‘s/dapper/edgy/g’ -i /etc/apt/sources.list
    produce: sed: -i may not be used with stdin
    sudo sed -e ‘s/dapper/edgy/g’ -i “” /etc/apt/sources.list

Leave a Reply