0

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?

2
  • Please add some good examples and the expected output and format it as code. Like this it's difficult to get what you want to do.
    – pLumo
    Commented Jan 22, 2019 at 12:31
  • Delete the rest of the line that matches, or delete from that line to the end of the file?
    – Jeff Schaller
    Commented Jan 22, 2019 at 13:48

3 Answers 3

3

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
1
  • I think that solved it! Still a bit tricky but good to handle. My workaround is to cut the lines to temp file with your code and after that i copy from temp file to estimated file with code "sed -n '/string/,$p' file >> otherfile".
    – diggidre
    Commented Jan 22, 2019 at 14:09
2

Or use ed!

ed -s file <<< $'/textb/,$w otherfile\n/textb/,$d\nw\nq'

Given your input file of:

texta

texta1

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

textb1

textc

textc1

After executing the ed command, file becomes:

texta

texta1

(there's a blank line at the end that disappears in the formatting here); and otherfile contains:

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

textb1

textc

textc1

The ed commands are:

  • /textb/,$w otherfile -- write that range of lines to otherfile
  • /textb/,$d -- delete that range of lines
  • w -- write out the changed file to disk
  • q -- quit ed
0

If you use this command sed -n '/string/,$p' file >> otherfile to extract all the lines from the one containing string to the end of the file ($) to an otherfile file.

The easiest way to extract the complement of that is to complement the match:

sed '/string/,$d' file >> someOtherDifferentFile

And if you want/need to update the original file just copy the result back.

Which is what the -i option to sed does, so, this will update the original file:

sed -i.bak '/string/,$d' file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .