4

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?

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

3 Answers 3

8

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.

2
  • 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, 2019 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? Jan 22, 2019 at 12:29
4
grep -A $(< $A wc -l) hotword $A >> $B
2
  • And what if the file contains more than 99 lines after the hotword?
    – Psychonaut
    Jan 22, 2019 at 8:36
  • @Psychonaut. Fixed. Jan 22, 2019 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 .