23

A simple question, but I can't find the answer. the zsh documentation overwhelms me :-(

function z ()
{
  echo ${1:s/the/THE}
}

$ z thethethe
THEthethe

...

How can I get all 'the' to be replaced with 'THE', not just the first occurrence? With zsh it's the easiest things that seem to be the hardest to find examples for.

5 Answers 5

34

This is a history expansion modifier, so add the g modifier immediately before s.

print -r -- ${1:gs/the/THE}

Alternatively, use the parameter expansion syntax where a double slash means a global substitution. In this case, the part after // is a wildcard pattern, whereas history expansion substitution takes a literal string (unless the histsubstpattern option is enabled).

print -r -- ${1//the/THE}
9

This should do the job:

VARIABLE=thethethe
print -r -- ${VARIABLE//the/THE}
THETHETHE
4

Thereyago, it had to be simple:

print -r -- ${1//the/THE}

... the double slash does it, and you can't fool around with " :s "

BTW, I'd sure like to thank the 'StackExchange' sites for existing. Of all the zillions of places one might ask a question, these are by far the best--one not only almost always gets answers, but those answers are invariably of the highest quality.

3

There are many answers, but none of them are comprehensive, so I felt like adding an answer that sums it all up.

Lower/Uppercasing

If you are trying to uppercase the string, the simplest way is to use:

> str="thethethe"
> upper="$str:u"
> echo $upper
THETHETHE

(Not part of the original question, but just in case) If you are trying to lowercase, the same goes for :l.

Replacing substrings

If you want to replace a single occurrence, use this:

> str="thethethe"
> echo ${str/the/man}
manthethe

If you add an extra slash between the variable and the test to substitute, it will replace all the occurrences:

> str="thethethe"
> echo ${str//the/man}
manmanman

Another option is to use the history modifiers, just like Gilles suggested:

> str="thethethe"
> echo ${str:gs/the/man}
manmanman
1

// works perfect if you're only trying to replace a specific word to all caps while leaving the rest of it untouched. If you are trying to convert everything to uppercase, you can use ":u" on the variable

SOME_ENV_VALUE='thethethe'
print -r -- $SOME_ENV_VALUE:u # outputs: THETHETHE

You can verify which modifiers you have available in the zsh expansion and substitution manual

man zshexpn

Or with

info zsh modifiers 

If you have the info pages installed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.