How to Use sed to Remove Last n Characters of Line


Often you may want to use sed to remove the last n characters from each line in a file.

You can use the following basic syntax to do so:

sed 's/.\{3\}$//' cities.txt

This particular example will delete the last 3 characters from each line in the file named cities.txt.

If you would like to modify the file in-place then you can add the -i flag as follows:

sed -i 's/.\{3\}$//' cities.txt 

Note that the s command in sed is used to substitute one pattern for another.

In this case, we substitute the last three characters of each line in the file with nothing, which effectively removes the last three characters from each line.

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

Example: Use sed to Remove Last n Characters of Line

Suppose that we have a text 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 last three characters from each line in the file.

We can use the following syntax to do so:

sed 's/.\{3\}$//' cities.txt

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

sed remove last n characters from each line in file

Notice that the last three characters have been removed from each line in the file.

To remove a different number of characters, simply change 3 to a different number.

For example, we can use the following syntax to remove the last 4 characters from each line:

sed 's/.\{4\}$//' cities.txt

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

Notice that the last 4 characters have been removed from each line in the file.

Related Tutorials

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

How to Use sed to Delete All Lines Containing Specific String
How to Use sed to Delete All Empty Lines in File
How to Use sed to Delete Specific Line Numbers from File

Leave a Reply