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

LinuxBash

Linux Problem Overview


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

Linux Solutions


Solution 1 - Linux

You can combine tail and head:

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

Solution 2 - Linux

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'

Solution 3 - Linux

This is the quickest way I found:

sed -i 1,2d filename

Solution 4 - Linux

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrebcaView Question on Stackoverflow
Solution 1 - LinuxFrédéric HamidiView Answer on Stackoverflow
Solution 2 - LinuxDebadityaView Answer on Stackoverflow
Solution 3 - LinuxfinferfluView Answer on Stackoverflow
Solution 4 - LinuxpizzaView Answer on Stackoverflow