Often you may want to use sed to remove the last character in a file.
You can use the following syntax to do so:
sed '$ s/.$//' employees.txt
This particular example will remove the last character from the last line of the file named employees.txt.
Here is how this syntax works:
- First, we use $ to match the last line of the file
- Then, we use the s command to perform a substitution
- We use . to match any character on the last line and we use $ to anchor that match to the end of the line, which allows us to specify the last character of the last line
- We then replace this last character with nothing, which effectively removes it from the file
The following example shows how to use this syntax in practice.
Example: Use sed to Remove the Last Character of a File
Suppose that we have a file named employees.txt that contains the ID values for various employees at some company.
We can use the cat command to view the contents of this file:

Now suppose that we would like to remove the last character of the file.
We can use the following syntax to do so:
sed '$ s/.$//' employees.txt
The following screenshot shows how to use this syntax in practice:

Notice that this returns the entire file with the last character removed from the last line.
Note that if you would like to save these changes to the file in-place then you can add the -i flag as follows:
sed -i '$ s/.$//' employees.txt
This will save the changes to the employees.txt file in-place.
Related Tutorials
The following tutorials explain how to perform other common tasks in sed:
How to Use sed to Insert Line at Specific Line Number
How to Use sed to Insert Empty Line in a File
How to Use sed to Insert Line with Leading Spaces
How to Use sed to Insert a Line After Match
