How does one remove any and all whitespace from the ends of a string in Zsh without spawning another process?
After looking at the documentation for expansion in Zsh (namely sections 14.3 Parameter Expansion and 14.8.1 Glob Operators)—also viewable via $ man zshexpn—I've written the following code:
${${var##[:space:]##}%%[:space:]##}
But Zsh doesn't seem to recognize the [:space:] glob operator. As per my understanding of the following statement in the documentation, it should:
In the expansions discussed below that require a pattern, the form of the pattern is the same as that used for filename generation; see Filename Generation. Note that these patterns, along with the replacement text of any substitutions, are themselves subject to parameter expansion, command substitution, and arithmetic expansion.
Is this a bug in Zsh or am I overlooking something?
For now, I'm just using ${${var## ##}%% ##} which at least substitutes any and all space characters at the ends.
I'm using Zsh 5.8.
You're really close.
(MS) (matching substring) parameter expansion flags.${(MS)var##[[:graph:]]*[[:graph:]]}
In the example below, the parameter we will strip leading/trailing whitespace from has the identifier var. Substitute this as necessary in your own code.
typeset var=$'\n\t abc def \n\t'
Printing a parameter stripped of any leading/trailing whitespace:
print -n -- ${(MS)var##[[:graph:]]*[[:graph:]]}
Output: abc def
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With