I have a file which is made up of several lines of text:
The first line The second line The third line The fourth line
I have a string which is one of the lines: The second line
I want to delete the string and all lines after it in the file, so it will delete The third line
and The fourth line
in addition to the string. The file would become:
The first line
I've searched for a solution on google, and it seems that I should use sed
. Something like:
sed 'linenum,$d' file
But how to find the line number of the string? Or, how else should I do it?
The rm command is used to delete files.
To begin with, if you want to delete a line containing the keyword, you would run sed as shown below. Similarly, you could run the sed command with option -n and negated p , (! p) command. To delete lines containing multiple keywords, for example to delete lines with the keyword green or lines with keyword violet.
If you don't want to print the matched line (or any following lines):
sed -n '/The second line/q;p' inputfile
This says "when you reach the line that matches the pattern quit, otherwise print each line". The -n
option prevents implicit printing and the p
command is required to explicitly print lines.
or
sed '/The second line/,$d' inputfile
This says "delete all lines from the output starting at the matched line and continuing to the end of the file".
but the first one is faster. However it will quit processing completely so if you have multiple files as arguments, the ones after the first matching file won't be processed. In this case, the delete form is better.
If you do want to print the matched line, but not any following lines:
sed '/The second line/q' inputfile
This says "print all lines and quit when the matched line is reached" (the -n
option (no implicit print) is not used).
See man sed for additional information.
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