Sed Script – Delete Text from Beginning of Line with Certain String

sedshell-script

I use sed -n '/string/,$p' file >> otherfile to copy text from a line with certain string to another file.

Now I want the copied text to be deleted in the original file. I tried different methods with sed and awk but nothing worked.

How to use sed to delete the text of a file from the beginning line with a certain string in it?

texta

texta1

textb    <- string, delete rest of the text from here

textb1

textc

textc1

or would it be easier to cut instead of copying with sed and what would be the command instead?

Best Answer

You can write an addressed range of lines to a new file, and then delete the range - the tricky part is preventing the d command from being treated as part of the output file name. In GNU sed, you can do that by splitting the write and delete into separate expressions using -e

IMPORTANT NOTE: this will truncate otherfile rather than appending to it

sed -i.bak -e '/string/,${w otherfile' -e 'd;}' file
Related Question