Delete everything after a certain line in bash

Viewed 8051

I was wondering if there was a way to delete everything after a certain line of a text file in bash. So say there's a text file with 10 lines, and I want to delete every line after line number 4, so only the first 4 lines remained, how would I go about doing that?

5 Answers

If I don't know the line number, merely the line content (I need to know that there is nothing below the line containing 'knowntext' that I want to preserve.), then I use.

sed -i '/knowntext/,$d' inputfilename

to directly alter the file, or to be cautious

sed '/knowntext/,$d' inputfilename > outputfilename

where inputfilename is unaltered, and outputfilename contains the truncated version of the input. I am not competent to comment on the efficiency of this, but I know that files of 20kB or so are dealt with faster than I can blink.

Related