Search code examples
bashshtail

Tail script to write out contents of a file from the end up to a matched pattern


I'm looking for a solution to a smple variant to this tail question...hoping someone will know the solution. Basically I want to tail a file until a string/pattern is matched and then write the contents out from the end of the file up until the line containing that pattern (or up to that pattern). The solution at this link, with a slight modification to re-direct output to a new file:

sh -c 'tail -n +0 --pid=$$ -f tmp.log | { sed "/pattern/ q" && kill $$ ;}' >& tmp.txt 

gave me the exact opposite (contains the file from the top upto the string/pattern match). Appreciate any ideas - thanks for your time.


Solution

  • OK...I think after looking around, I found what I think is the solution to my problem. Apologies for changing the definition of the problem mid-way (multiple occurrences of the pattern). Here's the fix using awk:

    awk '/pattern/{i++}i' tmp.log >& tmp.txt
    

    Thanks to everyone who commented/posted with ideas. Appreciate it.