8

I have a large file test.txt like this example:

foo
before ...
before some line 
foo something interesting bar
after some lines
after ...
bar

How 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)?

Pandya
  • 23,898
  • 29
  • 92
  • 144
rubo77
  • 27,777
  • 43
  • 130
  • 199
  • 1
    A slight nitpick (and clarification). `sed` and `grep` are not `bash` commands; they are separate commands, which can be invoked from any shell you happen to be using. – Bob Eager Jul 22 '17 at 09:33
  • [Show all the file up to the match](https://unix.stackexchange.com/q/11305) – don_crissti Jul 22 '17 at 10:20

1 Answers1

13
sed '/something interesting/,$d' < file > newfile

Which can be optimized to:

sed -n '/something interesting/q;p' < file > newfile

for sed to quit as soon as it finds the pattern.

Which with the GNU implementation of sed, as noted by @RakeshSharma, can be simplified to

sed '/something interesting/Q' < file > newfile

To 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)).

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • @RakeshSharma, good point. I've added it – Stéphane Chazelas Jul 22 '17 at 09:42
  • The first suggestion works perfectly, thanks. I spent some time to realize how to use it wit shell variable expansion: `sed "/${VAR}/,$ d"` - note the white space between `$` and `d`. – pa4080 Sep 14 '18 at 22:52
  • And the GNU sed command to edit in place would simply be `sed -i '/something interesting/Q' 'file'` – Sadi Jan 31 '21 at 13:30