I have a large file test.txt like this example:foobefore ...before some line foo something interesting barafter some linesafter ...barHow do I create a new file with just the lines before the first occurrence of the string something interesting with basic bash commands like sed or grep (not awk, I need this on an embedded device without awk)?
Deleting all lines after first occurrence of a string in a line
text processing
sed '/something interesting/,$d' < file > newfileWhich can be optimized to:sed -n '/something interesting/q;p' < file > newfilefor sed to quit as soon as it finds the pattern.Which with the GNU implementation of sed, as noted by @RakeshSharma, can be simplified tosed '/something interesting/Q' < file > newfileTo truncate the file in-place, with ksh93 instead of bash, you could do:printf '' <>; file >#'*something interesting*'<>; is like the standard <> redirection operator (open in read+write) except that the file is truncated at the end if the command is successful.<#pattern seeks to the start of the next line matching the pattern.(note that it seems to work (with ksh93u+ at least) with printf '' on stdout but not with some other builtin commands like true, : or eval. Looks like a bug. Also it can't be the last command of a script (another bug)).