How do you grep the last occurrence?

How do you grep the last occurrence?

6 Answers

  1. Print last occurence of x (regex): grep x file | tail -1.
  2. Alternatively: tac file | grep -m1 x.
  3. Print file from first matching line to end: awk ‘/x/{flag = 1}; flag’ file.
  4. Print file from last matching line to end (prints all lines in case of no match): tac file | awk ‘! flag; /x/{flag = 1};’ | tac.

How do I count the number of lines in a UNIX pattern?

Using grep -c alone will count the number of lines that contain the matching word instead of the number of total matches. The -o option is what tells grep to output each match in a unique line and then wc -l tells wc to count the number of lines.

How to find the last line in a file?

Another way to find the last line is to reverse the file and output the first match. The quickest way to do this would be get the output last 1 (or more) lines from the files and then grep through that. So –

How to grep the last occurrence of a line pattern?

You could also delete to the beginning of the matched line prior to the line deletions with d0 in case there were multiple matches on the same line. if you wanna do awk in truly hideous one-liner fashion but getting awk to resemble closer to functional programming paradigm syntax without having to keep track when the last occurrence is

How to select one line from multiple files in grep?

Sort has a uniq option that allows you to select just one line from many. Try this: Explanation: Grep will return one line for each match in a file. This looks like: You can treat this as a sort of table, in which the first column is the filename and the second is the match, where the column separator is the ‘:’ character.

How do you save the last line in a line in Bash?

Saves the last x and what follows in the hold space and prints it out at end-of-file. You could also delete to the beginning of the matched line prior to the line deletions with d0 in case there were multiple matches on the same line.