Delete first line from file in shell script

By | 22nd August 2020

We can delete the first line in a file using ‘sed’ command in the shell script. Let us see with the help of a test file called ‘sample.txt’. Here are the contents of the text file.

$ cat sample.txt
first line
second line
third line

Option 1: Delete and save in a new file

In this option, a new file will be created with the modified data and the original file will remain the same.

sed – stream editor, ‘1d’ – delete first line. If you want to delete the first two lines, use ‘1,2d’

$ sed '1d' sample.txt > newfile.txt

Here, the original file sample.txt has 3 lines and the new file newfile.txt will have only two lines.

$ cat sample.txt
first line
second line
third line
$ cat newfile.txt
second line
third line

Option 2: Delete and save in the same file

In this option, the content will be deleted in the same file. The command should have an extra ‘-i’ after ‘sed’

$ sed -i '1d' sample.txt

The above command will delete the first line in the sample.txt file.

$ cat sample.txt
second line
third line

NOTE: If you are running this in Mac, you need to add ‘-e’ after ‘-i’. The command will look like

$ sed -i -e '1d' sample.txt

Leave a Reply

Your email address will not be published. Required fields are marked *