How to delete all the lines after the last occurence of pattern?
问题 i want to delete all the lines after the last occurence of pattern except the pattern itself file.txt honor apple redmi nokia apple samsung lg htc file.txt what i want honor apple redmi nokia apple what i have tried sed -i '/apple/q' file.txt this deletes all the line after the first occurence of pattern - honor 回答1: Simple, robust 2-pass approach using almost no memory: $ awk 'NR==FNR{if (/apple/) hit=NR; next} {print} FNR==hit{exit}' file file honor apple redmi nokia apple If that doesn't