Commands on how to delete a first line from a text file using bash shell

In this short config we will show a multiple options on how to remove a first line from a text file. Here is the content of our sample file.txt.

$ cat file.txt 
line1
line2
line3
line4



We can use a sed command to remove a first line of the above file:

$ sed '1d' file.txt 
line2
line3
line4

The above will produce STOUT thus you will need to redirect STOUT to a new file:

$ sed '1d' file.txt > mynewfile.txt

or use -i option to change file in-place:

$ sed -i '1d' file.txt 
$ cat file.txt 
line2
line3
line4

Onother option to remove a first line of the file is by use of tail command:

$ tail -n +2 file.txt 
line2
line3
line4

Once again use redirection of STDOUT to form a new file without a first line. Yet an another example on how to remove a first line from a text file is to use ed text editor:



$ cat file.txt 
line1
line2
line3
line4
$ printf "%s\n" 1d w q | ed file.txt
24
18
$ cat file.txt 
line2
line3
line4

What happened is that we used printf command to produce delete(1d), save(w) and quit(q) commands and pipe them to ed command. In the following example we remove a first line from the file using vi text editor:

$ cat file.txt
line1
line2
line3
line4
$ vi -c ':1d' -c ':wq' file.txt
OR BETTER
$ ex -c ':1d' -c ':wq' file.txt
$ cat file.txt
line2
line3
line4

The options on how to remove a first line from a file just keep piling up. Here we use a awk command the do the same thing:

$ cat file.txt
line1
line2
line3
line4
$ awk 'NR > 1 { print }' file.txt
line2
line3
line4


We will finish with an example on how to remove a fisrt line from all files in your directory:

$ ls
file1.txt  file2.txt

We have to files located in our current working directory. Each file contains 4 line:

$ grep line *
file1.txt:line1
file1.txt:line2
file1.txt:line3
file1.txt:line4
file2.txt:line1
file2.txt:line2
file2.txt:line3
file2.txt:line4

We can use a for loop to remove a first line from each file:

$ for i in $( ls file*.txt ); do sed -i '1d' $i; done
$ grep line *
file1.txt:line2
file1.txt:line3
file1.txt:line4
file2.txt:line2
file2.txt:line3
file2.txt:line4


Comments and Discussions
Linux Forum