Often you may want to extract the substring before a specific character in Bash.
You can use the following methods to do so:
Method 1: Extract Substring Before Specific Character (inclusive)
echo $my_string | grep -o '.*Zach'
This particular example will extract all text before and including the substring Zach in the string variable named my_string.
Method 2: Extract Substring Before Specific Character (not inclusive)
echo $my_string | grep -oP '.*(?=Zach )'
This particular example will extract all text before the substring Zach (not including Zach) in the string variable named my_string.
Note that we used the grep command with the operator -o to specify that we only want to return the part of the matching string that matches the pattern that we specified.
The following examples show how to use each method in practice.
Example 1: Extract Substring Before Specific Character (Inclusive)
Suppose that we have the following string:
- The employee named Zach has 10 years of experience
And suppose that we would like to extract all of the text before and including Zach to get the following result:
- The employee named Zach
We can use the following syntax to do so:
my_string="The employee named Zach has 10 years of experience"
echo $my_string | grep -o '.*Zach'
The following screenshot shows how to use this syntax in practice:

Notice that we’re able to extract the following text:
- The employee named Zach
Example 2: Extract Substring Before Specific Character (Not Inclusive)
Suppose that we have the following string:
- The employee named Zach has 10 years of experience
And suppose that we would like to extract all of the text before Zach to get the following result:
- The employee named
We can use the following syntax to do so:
my_string="The employee named Zach has 10 years of experience"
echo $my_string | grep -oP '.*(?=Zach )'
The following screenshot shows how to use this syntax in practice:

Notice that we’re able to extract the following text:
- The employee named
Note that in this example we extract all text before the pattern that we specified, so we did not include the pattern Zach in the output.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Extract Text Between Two Strings
Bash: How to Replace Multiple Characters in String
Bash: How to Replace All Occurrences of String in File
