How to delete first two lines and last four lines

2020-02-16 06:41发布

问题:

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

回答1:

You can combine tail and head:

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


回答2:

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'


回答3:

This is the quickest way I found:

sed -i 1,2d filename


回答4:

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


标签: linux bash