DEV Community

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

Top comments (0)