DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Gabor Szabo
Gabor Szabo

Posted on

CLI tools: Replace snake by camel in a text file

I have a file that has the word "snake" in it

There is a snake in the first line.
No such word in the second line.
Another snake in the 3rd line.
There is a blue snake and a red snake here.
Enter fullscreen mode Exit fullscreen mode

This one-liner that you can run on the command line will replace the word "snake" by the word "camel" in the file:

$ perl -i -p -e 's/snake/camel/g' snakes_or_camels.txt
Enter fullscreen mode Exit fullscreen mode

This one-liner will create a backup of the original file before making the changes.

$ perl -i.bak -p -e 's/snake/camel/g' snakes_or_camels.txt
Enter fullscreen mode Exit fullscreen mode
  • -i means "inplace editing"
  • -i.bak means "copy to .bak then inplace editing"
  • -p means (in rough terms) "What ever you do, do it on every line of data."
  • -e means "execute the following code".
  • s/snake/camel/g is a substitution. The g at the end means globally. Without that only the first snake would be replaced.

The result is

There is a camel in the first line.
No such word in the second line.
Another camel in the 3rd line.
There is a blue camel and a red camel here.
Enter fullscreen mode Exit fullscreen mode

If you'd like to learn more about Perl check out my Perl Tutorial

Oldest comments (0)

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: