How to Remove First Character from String in Bash (With Example)


Often you may want to use Bash to remove the first character from a string.

You can use the following methods to do so:

Method 1: Remove First Character from String Variable

my_string="${my_string:1}"

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

Method 2: Remove First Character from Each String in File

cut -c2- < cities.txt

This particular example will remove the first character from each string in the file named cities.txt.

Note that this method uses the cut command to return only the characters (-c) on each line of the file starting from the second character to the last character (2-) in the line.

The following examples show how to use each method in practice.

Example 1: Remove First Character from String Variable

Suppose we have the following string stored in a variable named my_string in Bash:

  • Dallas Mavericks

We can use the following syntax to remove the first character from this string:

my_string="Dallas Mavericks"
my_string="${my_string:1}"

echo $my_string

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

Bash remove first character from string variable

We can see that this returns the following string:

  • allas Mavericks

Notice that the first character has been removed from the original string.

Example 2: Remove First Character from Each String in File

Suppose that we have a file named cities.txt in our current directory that contains the names of various U.S. cities.

We can use the cat command to view the contents of this file:

Bash remove first character from string

Suppose that we would like to remove the first letter from each line in the file.

We can use the following syntax to do so:

cut -c2- < cities.txt

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

Bash remove first character from each string in file

Notice that this removes the first character from each line in the file.

If you would like to save these results to a new file then you can use the > command as follows:

cut -c2- < cities.txt > cities_new.txt

This particular example will remove the first character from each line in the cities.txt file and save the results to a new file named cities_new.txt.

Related Tutorials

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

Bash: How to Remove Last N Characters from String
Bash: How to Get Last N Characters from String
Bash: How to Get First N Characters from String

Leave a Reply