In this tutorial, we will explore the various techniques and commands to work with strings and patterns in Zsh scripts.
String Basics
In Zsh, we can assign the values to string variables using the “=” operator. This is a common use case when defining the variables as shown in the following example:
We must enclose a string in single or double quotes to let the shell know that the value of the variable is as sting.
We can also determine the length of a string using the ${#variable} notation. For instance:
length=${#str }
echo "Length of the string is $length"
This returns the length of the string as 13.
The next part of the string manipulation technique in Zsh is substring extraction. We can extract a substring from a given string using the ${variable[start,length]} notation.
An example is as follows:
substring=${str [7,5]}
echo "Substring: $substring"
Output:
String Concatenation
To concatenate two strings, we can use the “=” operator or simply place them together.
string2=" World"
concatenated="${string1}${string2}"
echo $concatenated
This joins the specified strings into a single string entity.
Pattern Matching
Asterisk (*) Wildcard
The first wildcard that we can use in pattern matching is the asterisk. The “*” wildcard matches zero or more characters. For example:
echo $pattern
This matches the files like “file1.txt”, “file123.txt”, etc.
Question Mark (?) Wildcard
The second is the question mark wildcard. For this one, the “?” wildcard matches a single character. For example:
echo $pattern
This matches the files like “file1.txt”, “fileA.txt”, etc.
Character Classes ([])
Third, we have the character classes that allow us to specify a set of characters to match against. For instance:
echo $pattern
In this case, the pattern matches the files like “1file.txt”, “2file.txt”, etc.
Regular Expressions
Regular expressions provide powerful pattern matching capabilities in Zsh. By default, Zsh supports basic regular expressions with the “=~” operator.
if [[ $string =~ ^m.SQL $ ]]; then
echo "Match found!"
else
echo "No match found."
fi
The given code matches MySQL.
You can also enable the extended regular expressions with the “set -o extendedglob” command. For example:
string="MySQL"
if [[ $string =~ m(S|Q)L ]]; then
echo "Match found!"
else
echo "No match found."
fi
Parameter Expansion
Parameter expansion is a powerful feature in Zsh to manipulate the strings.
Conclusion
In this tutorial, we covered the most fundamental concept of working with advanced string manipulation and pattern matching.