DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Updated on

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

Latest comments (0)