I am trying to delete first two lines and last four lines from my text files. How can I do this with Bash?
-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)
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.
You can combine tail and head:
$ tail -n +3 file.txt | head -n -4 > file.txt.new && mv file.txt.new file.txt
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With