Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete first two lines and last four lines from a text file with bash?

Tags:

linux

bash

I am trying to delete first two lines and last four lines from my text files. How can I do this with Bash?

like image 361
rebca Avatar asked May 05 '12 10:05

rebca


People also ask

How do you delete the first and last line in Unix?

-i option edit the file itself. You could also remove that option and redirect the output to a new file or another command if you want. 1d deletes the first line ( 1 to only act on the first line, d to delete it) $d deletes the last line ( $ to only act on the last line, d to delete it)

How do I delete a range of lines in Linux?

The sed command can remove the lines of any range. For this, we just have to enter 'minimum' and 'maximum' line numbers. In this example, we will remove the lines ranging from 4 to 7 numbers. After removing these ranges of lines, our file will look like this.


2 Answers

You can combine tail and head:

$ tail -n +3 file.txt | head -n -4 > file.txt.new && mv file.txt.new file.txt 
like image 74
Frédéric Hamidi Avatar answered Sep 30 '22 13:09

Frédéric Hamidi


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' 
like image 41
Debaditya Avatar answered Sep 30 '22 12:09

Debaditya