DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

6 4

Tips to use "sed" command

When we used the sed command in our pipeline, we had some surprises and took a little bit of times to understand our issue.

So here is some tips that I learned from these searches.


Change every occurrence in a file

As said in the title, the following command will change every occcurrence of "AAAA" by "BBBB" in the "file.json" file.

sed -i 's/AAAA/BBBB/g' file.json
Enter fullscreen mode Exit fullscreen mode

Change first occurrence of each line

Here is the biggest issue that we had. Without the "g" at the end of the replace option, the following command will only replace the first occurrence of "AAAA" in each line.

sed -i 's/AAAA/BBBB/' file.json
Enter fullscreen mode Exit fullscreen mode

Change first occurrence

The following command is to replace the first occurrence of "Apple" by "Banana". But this replacement will only occur between the index 0 and the first occurrence of Apple.

sed '0,/Apple/{s/Apple/Banana/}' input_filename
Enter fullscreen mode Exit fullscreen mode

So you can easily customize it to replace the first occurrence of Apple after a particular index or specific words.


I hope it will help you! 🍺


You want to support me?

Buy Me A Coffee

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay