Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the global flag for in sed?

I’ve come to know the global (/g) flag to mean the action should take place globally in a file.

If I want to replace all instances of "hello world" with "goodbye space", I would add /g on the end of the statement.

That makes sense. However…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was writing a sed replace command and noticed that even if I didn’t include /g it would still replace all instances in a file. Below is the contents of my .txt file:

hello there
how is life
today is over
today is over
don't be sad
today is over
tomorrow is a new day

Now, I want to file all of these "today is over" lines and replace them with "tomorrow will begin". Therefore, I wrote the below code:

YOUR_FILE='testing.txt'
LINE="today is over"

sed -i "" "s/$LINE/tomorrow will begin/" $YOUR_FILE

Despite NOT including the global flag at the end, it still replaces all instances of today is over with tomorrow will begin.

Can someone explain this behavior to me as I haven’t been able to find anything about it. Why does it replace all instances even when I omit the /g part at the end?

Alternatively, if I wanted to only remove the first instance, how would I go about specifying that?

I am doing this on a Mac.

>Solution :

The global flag allows sed to replace multiple matches in the same line.

$ echo 'world world' > somefile
$ sed 's/world/hello/' somefile
hello world
$ sed 's/world/hello/g' somefile
hello hello
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading