Remove last character from all lines in a file

October 28, 2015 — 2 Comments

There are a couple ways to remove the last character from a file – scratch that.. tons of ways.. but, we’ll show you a couple ways today.

So, you have a long file with an extra character at the end of each line. We’re big fans of both sed and awk so we’ll show you how to use both! The awk command is a bit longer but once you’re familiar with awk’s print function, you almost go with it every time anyway. It’s good to know both ways.

Here’s the first 5 lines of our file:
—–
linuxos.pro is the best?
linuxos.pro shows us how to use linux?
i love linuxos.pro?
4th line in a linuxos.pro lesson?
The trash guys will take my broken washer?
—–

sed:
Let’s fix that file – first, using sed. Here, we’re replacing any character at the end of the line with ‘nothing’.. not even a space.

Now, we have this:
—–
linuxos.pro is the best
linuxos.pro shows us how to use linux
i love linuxos.pro
4th line in a linuxos.pro lesson
The trash guys will take my broken washer
—–

awk:
Now, let’s start over.. and use awk to do the same thing. We look at the file and see that we want to get rid of the ‘?’ in the file.. so we use the ? as the separator and print what’s before it (would be column 1).

We do now have some extra steps.. we used awk to print the first column, then put the output back into the original file.

In this case, sed worked better.. but again, it’s important to know multiple ways to do things in Linux!




2 responses to Remove last character from all lines in a file

  1. Well, the awk approach won’t work because opening the file with > for stdout redirection immediately resets it.

Leave a Reply