Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

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.

like image 936
Matt Croak Avatar asked Sep 20 '25 16:09

Matt Croak


1 Answers

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
like image 134
jirassimok Avatar answered Sep 22 '25 09:09

jirassimok