Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command sed using g

I am new to Linux. I was debugging some code. I encountered the following command:

PROGRAM_ID=$(echo $PROGRAM_ID|sed 's/-/,/g')

Can anybody explain what the g represents here? I understand hyphen is being replaced with comma.

like image 527
user1942215 Avatar asked Jul 28 '26 07:07

user1942215


2 Answers

The /g flag means, perform the substitution globally on a line. Without that flag, only the first hyphen on every line would get substituted.

A better way with Bash would be

PROGRAM_ID=${PROGRAM_ID//-/,}

but if you have to be portable to Bourne shell in general, this replacement facility is not available.

(In which case you should take care to keep "$PROGRAM_ID" in double quotes in the echo.)

like image 173
tripleee Avatar answered Jul 30 '26 00:07

tripleee


It's easy to see how g (global) works with these two examples:

$ echo "test-one-two-three" | sed 's/-/,/g'
test,one,two,three
$ echo "test-one-two-three" | sed 's/-/,/'
test,one-two-three

Without g, only the first hyphen is replaced.

like image 36
Jotne Avatar answered Jul 29 '26 22:07

Jotne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!