Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming whitespace from the ends of a string in Zsh

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.

like image 629
Tyler Crompton Avatar asked Nov 05 '25 20:11

Tyler Crompton


1 Answers

You're really close.

  1. You need to modify your POSIX Basic Regular Expression character class syntax a bit
  2. You can simplify the expression by using the (MS) (matching substring) parameter expansion flags.
${(MS)var##[[:graph:]]*[[:graph:]]}

Solution

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

like image 61
chahu418 Avatar answered Nov 07 '25 16:11

chahu418



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!