Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all lines after a line number

Tags:

string

bash

match

I have a file like this:

string log 1 
string log 2
string match
string log 4
string match
string log 5
string log 6

I need to get all the lines after the last string match. How can I do it in bash?

like image 829
Rfraile Avatar asked Feb 14 '12 09:02

Rfraile


People also ask

How do you print a range of lines in Unix?

p - Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option. n - If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input.

How do I grep a specific line number in Linux?

The -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.


1 Answers

First, find the last string match:

line=$(grep -n 'string match' myFile | cut -d: -f1 | tail -1)

Then, print all lines up to that last string match:

sed -n "1,${line}p" myFile

If you need all lines after last match:

sed -n "$((line+1))"',$p' myFile
like image 88
mouviciel Avatar answered Sep 29 '22 07:09

mouviciel