4

This question already has an answer here:

My goal is to extract text from a specific line with a hotword (don't know how to call it else) in it. The line number can vary because its an weekly updated file. When hotword is detected it should copy this line and all following text to another file.

Could this be done by sed, awk or something else?

marked as duplicate by Jeff Schaller, RalfFriedl, msp9011, Archemar, elbarna Jan 24 at 2:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Provide an example of the text, indicate the word that you are looking for, and give the expected output. – Nasir Riley Jan 21 at 23:35
9

grep -A 10 can be used to print the line with the matching word and ten lines after (you can substitute 10 with whatever number you want) but as you haven't indicated how many lines are in the file, you can use the following instead:

sed -n '/word/,$p' file >> file2

That will print the line with the word and all of the lines afterwords and then append them to another file. This way, you don't have to account for the total number of lines if the file contains a large number of lines such as 1,000 or more.

  • OK thx that's great. Is there a way not to copy the text lines but to cut them out. is that possible in just one command or do i have to purge after i copied text with sed? – diggidre Jan 22 at 9:33
  • @diggidre Do you mean that you just want to send them standard output as in only having them appear onscreen or do you mean that you just want to remove them from the file? – Nasir Riley Jan 22 at 12:29
3
grep -A $(< $A wc -l) hotword $A >> $B
  • And what if the file contains more than 99 lines after the hotword? – Psychonaut Jan 22 at 8:36
  • @Psychonaut. Fixed. – user1133275 Jan 22 at 12:43
0

Another option is to use awk:

awk "/word/, 0" infile >outfile

This copies the range of lines starting from the first one containing ‘word’, and ending never (hence the 0).

Not the answer you're looking for? Browse other questions tagged or ask your own question.