• Skip to main content

Uly.me

cloud engineer

  • Home
  • About
  • Archives

replace

Vi Search and Replace

April 3, 2022

How to do search and replace in Vim.

Search for “foo” and replace it with “bar” in the current line. Use :s

:s/foo/bar/g

:s/foo/bar/g

Search for “foo” and replace it with “bar” in the entire document. Use :%s

:%s/foo/bar/g

:%s/foo/bar/g

You can also pipe instead of forward slash. Useful if your search contains a /.

:%s|foo/|bar|g

:%s|foo/|bar|g

Filed Under: Linux Tagged With: entire, file, replace, search, vim

Modify a line using sed

May 11, 2021

Here’s how to modify a line in a file using sed.

sed -i 's/replace me.*/with this text/' /path/to/a/file.txt

sed -i 's/replace me.*/with this text/' /path/to/a/file.txt

Filed Under: Linux Tagged With: line, modify, replace, sed

Replace spaces with comma

February 4, 2020

Here’s a simple sed command to replace multiple spaces into a comma delimited file.

sample.txt

one       two
three     four

one two three four

The sed command.

sed 's/ \+ /,/g' sample.txt > sample2.txt

sed 's/ \+ /,/g' sample.txt > sample2.txt

sample2.txt

one,two
three,four

one,two three,four

Filed Under: Linux Tagged With: comma, find, replace, sed, spaces, tab

Mass Find and Replace

March 9, 2017

There are situations when you have to do a mass find and replace on your database. Let’s say you’re really, really bad speller. You just recently found out that you’ve been spelling a word for wrongly for years. To avoid embarrassment, you decide to do a search and replace. Unfortunately, you found out that there are hundreds of posts that contains that misspelled word. Instead of editing each post which is time consuming, you decide to run a mass find and replace against the database. In this example, we will replace the word ‘dawg’ with ‘dog.’

UPDATE wp_posts SET post_content = REPLACE ( post_content, 'dawg', 'dog');

UPDATE wp_posts SET post_content = REPLACE ( post_content, 'dawg', 'dog');

I highly recommend that you back up your database first. I also recommend that you run it on a test database first before running it on a production environment, because a mass update is quite dangerous if you’re not sure what you are doing. If you’re a WordPress user, there’s a plugin called Search and Replace that will do the same thing. That might be easier for most people who don’t have access to MySQL command line or PHPMyAdmin.

Filed Under: PHP, WP Tagged With: mysql, replace

  • Home
  • About
  • Archives

Copyright © 2023