Bash: How to Get First N Characters from String


Often you may want to use Bash to get the first N characters from a string.

The easiest way to do so is by using the cut command, which allows you to “cut” out specific sections from strings.

Here are two common ways to use the cut command to get the first N characters from a string:

Method 1: Get First Character from String

echo $my_string | cut -c1

This particular example will get just the first character from the string variable named my_string.

Method 2: Get First N Characters from String

echo $my_string | cut -c1-4

This particular example will get the first four characters from the string variable named my_string.

Note: We use the -c operator with the cut command to specify that we’d like to cut characters as opposed to something else like -b, which cuts bytes.

The following example shows how to use each of these methods in practice.

Example 1: How to Get First Character from String in Bash

Suppose we have the following string that represents the employee ID for a manager at a particular company:

  • Manager1430Department15

Suppose that we would only like to get the first character from this string.

We can use the following syntax to do so:

employee_ID="Manager1430Department15"
echo $employee_ID | cut -c1

The following screenshot shows how to use this syntax in practice:

Bash get first character from string

Notice that this returns M, which is the first character in the string.

Example 2: How to Get First N Characters from String in Bash

Once again, suppose we have the following string:

  • Manager1430Department15

Suppose that we would like to get the first four characters from this string.

We can use the following syntax to do so:

employee_ID="Manager1430Department15"
echo $employee_ID | cut -c1-4

The following screenshot shows how to use this syntax in practice:

Bash get first N characters from string

Notice that this returns Mana, which represents the first four characters in the string.

Note: To get a different number of characters from the beginning of the string, simply replace the 4 with a different number.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Check if String Starts with Specific Value
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String

Leave a Reply