search and replace
November 1st, 2006 mysurface Posted in Misc, sed, sudo, Text Manipulation, vi, vim | Hits: 33043 | 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/dapper/edgy/g
%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.







November 7th, 2006 at 11:40 pm
there is still have another way – called perl way :p
sudo perl -pi -e ‘s/dapper/edgy/g;’ xyz
November 19th, 2006 at 7:54 pm
[...] 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. [...]
January 27th, 2010 at 2:11 pm
sudo sed -e ‘s/dapper/edgy/g’ -i /etc/apt/sources.list
produce: sed: -i may not be used with stdin
while
sudo sed -e ‘s/dapper/edgy/g’ -i “” /etc/apt/sources.list
works.