Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globally replacing a string

Tags:

vi

I would like to use the global command 'g' to replace a string, e.g. replace hello with world I execute the command: s/hello/world/g I used this command before in nvi (now I only have vi) and it worked. This time however, the command executes only on the words on one line, not throughout the file.

I am using t shell.

Thank you.

like image 646
user2145860 Avatar asked Jun 16 '26 10:06

user2145860


2 Answers

In regular vi, you need to prefix the command with % to operate on every line:

:%s/hello/world/g

Note that % is equivalent to the explicit range 1,$ in SteveP's answer, in case you wondered what the difference is.

like image 160
chepner Avatar answered Jun 21 '26 06:06

chepner


In vi you could precede the command with a % to make the search and replace take place over the entire file.

%s/hello/world/g

Use with caution obviously :)

like image 25
squiguy Avatar answered Jun 21 '26 05:06

squiguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!