Often you may want to use Bash to remove the first and last line from a file.
You can use the following basic syntax to do so:
sed -i '1d;$d' teams.txt
This particular example removes both the first and last line from the file in the current directory named teams.txt.
Here is what the various sed commands do:
- -i: Modifies the file in-place
- 1d: Matches line 1 and then deletes ( d ) it
- $d: Matches the last line ( $ ) in the file and then deletes (d) it
The following example shows how to use this syntax in practice.
Example: How to Remove First and Last Line from File in Bash
Suppose that we have a file in our current directory named teams.txt that contains the names of various basketball teams.
We can use the cat command to view the contents of this file:

Suppose that we would like to remove both the first and last line from the file.
We can use the following syntax to do so:
sed -i '1d;$d' teams.txt
The following screenshot shows how to use this syntax in practice:

Notice that when we use the cat command once again to view the updated file we can see that the first and last lines have been removed.
Specifically, we can see:
- The first line that contained Dallas Mavericks has been removed.
- The last line that contained Orlando Magic has been removed.
Note that you could also use the > command to save these results to a new file instead of modifying the original file in-place:
sed '1d;$d' teams.txt > teams_new.tx
This particular example would remove the first and last lines from the teams.txt file and save the results to a new file named teams_new.txt.
Feel free to use whichever method you prefer.
Related Tutorials
The following tutorials explain how to perform other common tasks in sed:
How to Use sed to Replace All Text After Match
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace Last Occurrence of Character in String
