In a file like this one :...Pattern2:TheWrongBarfoo Pattern2:TheRightBarfoo First Patternfoo...I need to find the last occurrence of Pattern2 that is before First Pattern which would be in this case Pattern2:TheRightBarMy first idea is to get all the remaining file before First pattern with :sed -e '/First Pattern/,$d' myfile | tac | grep -m1 Pattern I need to getIsn't there a way to optimise this code?
Get the last occurrence of a pattern before another pattern
text processing
Finds the line count of First Pattern, then uses head to display lines above it, pipes through tac and greps it.head --lines=+$(grep -nm1 First Pattern file | cut -d\: -f1) file | tac | grep -m1 Pattern2 Eg.head --lines=+6 file | tac | grep -m1 Pattern2 This is more reliable then using -m 1000000 in grep.Since speed is important to OP, I checked the run time and it also appears to be faster then all other current answers (on my system)wc -l file25910209 filetime awk '/Pattern2/ {line=$0; next}; /First Pattern/ {print line; exit}' filePattern2:TheRightBarreal  0m2.881suser  0m2.844ssys 0m0.036stime sed '/Pattern2/h;/First Pattern/!d;x;/Pattern2/!d;q' filePattern2:TheRightBarreal  0m5.218suser  0m5.192ssys 0m0.024stime (grep -m1 First Pattern file -B 10000000 | tac | grep -m1 Pattern2)real  0m0.624suser  0m0.552ssys 0m0.124stime (head --lines=+$(grep -nm1 First Pattern file | cut -d\: -f1) file | tac | grep -m1 Pattern2)Pattern2:TheRightBarreal  0m0.586suser  0m0.528ssys 0m0.160s