6

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
user1942215
  • 87
  • 1
  • 8
  • Your original question had an unrelated syntax error which I edited out. You can't have whitespace on either side of the equals sign; see e.g. https://stackoverflow.com/questions/2268104/command-not-found-error-in-bash-variable-assignment – tripleee Nov 23 '21 at 10:33

2 Answers2

7

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

tripleee
  • 175,061
  • 34
  • 275
  • 318
3

Its easy to see how g (global) works with these two example:

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

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

Without the g it only replace the first hit.

Jotne
  • 40,548
  • 12
  • 51
  • 55