How to remove the first two lines and the last four lines from a text file using bash?

I am trying to remove the first two lines and the last four lines from my text files. How to do it using Bash?

+49
linux bash
May 05 '12 at 10:22
source share
4 answers

You can combine tail and head :

$ tail -n +3 file.txt | head -n -4 > file.txt.new && mv file.txt.new file.txt 
+72
May 05 '12 at 10:28
source share

Head and tail

 cat input.txt | tail -n +3 | head -n -4 

Sed solution

 cat input.txt | sed '1,2d' | sed -n -e :a -e '1,4!{P;N;D;};N;ba' 
+16
May 05 '12 at 11:29
source share

This is the fastest way I've found:

 sed -i 1,2d filename 
+7
Aug 09 '13 at 20:35
source share

You can invoke the ex editor from the bash command line using the following example. Note that a document is used here to complete the list of ex commands.

 ex text.file << EOF 1,2d $ -3,.d x EOF 
+2
May 6 '12 at 11:32 a.m.
source share



All Articles