Bash: How to Remove First and Last Characters from String


Often you may want to use Bash to remove the first and last characters from a string.

The easiest way to do so is by using sed with the following syntax:

sed -e 's/^.//' -e 's/.$//' cities.txt

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

Here is what the various commands do:

  • -e: Specifies that the string that follows should be interpreted as a sed expression
  • s/^.//: Used to “substitute” the first character ( ^. ) with nothing
  • s/.$//: Used to “substitute” the last character ( .$ ) with nothing

The following example shows how to use this syntax in practice.

Example: Use Bash to Remove First and Last Characters from String

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

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

Suppose that we would like to remove the first and last characters from each city name in the file.

We can use the following syntax to do so:

sed -e 's/^.//' -e 's/.$//' cities.txt

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

Bash remove first and last characters from string

Notice that the first and last character have been removed from each city name in the file.

Also note that you could use the > command to save these results to a new file:

sed -e 's/^.//' -e 's/.$//' cities.txt > cities_new.txt

This syntax would remove the first and last character from each city name in the file named cities.txt 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 Extract Text Between Two Strings
Bash: How to Replace Multiple Characters in String
Bash: How to Replace All Occurrences of String in File

Leave a Reply