Skip to content
Ksh93 string processing

Ksh93 string processing

October 24, 2026

Ksh93 string processing

replace

Batch add additional characters before special characters

Bash cannot retain the original characters when replacing, but ksh(ksh93) can do it!

# Add \[, \], \ in front of [, ], and \ in the variable `part`
key_q+=${part//@(['[]\'])/\\\1}

Core syntax breakdown:

  • //: Indicates global replacement (if only a single / is written, only the first match will be replaced).

  • @(...): ksh93’s extended pattern matching operator, which means “match any subpattern within the brackets”.

  • ['[]\']: The brackets define the character set to be matched - square brackets [, ] and backslash .

  • \: Replacement target. Where is a backreference (Backreference), representing the original character itself that is currently matched; the preceding \ is used to output a literal backslash.

For example: the original string is: ][ .\\[]][], and the converted string becomes: \]\[ .\\\\\[\]\]\[\].

This purely built-in string replacement method is completely based on memory operations and has zero external process overhead (Zero Fork). It is one of the killer features of ksh93 for efficient text processing. However, please note that when using this replacement function, ensure that all variables have been initialized.

Similar replacements have the following 5 formats:

  • @(...) (match one of them exactly)

  • *(...) (match zero or more times)

  • +(...) (match one or more times)

  • ?(...) (match zero or one time)

  • !(...) (reverse match, exclude content in parentheses)

Let’s look at another example:

str="user=admin"

result=${str//+([a-z])=+([a-z])/[\2] -> (\1)}
print -- "$result"
# Output result: [admin] -> (user)

A similar function is called extglob matching in bash, and it is turned off by default. It needs to be turned on through the shopt command. In bash, it is actually a semi-finished product that can match but the replaced characters cannot contain the original characters. It is not as powerful as in ksh. These functions in ksh are available by default.


✍️ Author of this article:秦大炮 (Qindapao)

Technical exchanges and reprints are welcome. Please indicate the source when reprinting and retain the following hard-core contact information.


Last updated on