rebca
rebca

Reputation: 1189

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

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

Upvotes: 68

Views: 85563

Answers (4)

finferflu
finferflu

Reputation: 1378

This is the quickest way I found:

sed -i 1,2d filename

Upvotes: 14

Debaditya
Debaditya

Reputation: 2497

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'

Upvotes: 21

pizza
pizza

Reputation: 7630

You can call the ex editor from the bash command line using the following sample. Note it uses a here document to end the list of commands to ex.

ex text.file << EOF
1,2d
$
-3,.d
x
EOF

Upvotes: 3

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262939

You can combine tail and head:

$ tail -n +3 file.txt | head -n -4 > file.txt.new && mv file.txt.new file.txt

Upvotes: 92

Related Questions