简体   繁体   中英

How to grep a string after a specified line number?

I have a large text file, I want to see the lines containing "time spent" in this text file, I use:

grep -in "time spent" myfile.txt

But I'm interested only in the lines after 50000. In the output I want to see lines after 50000 and that contain "time spent". Is there a way to do this?

你可以尾随它,然后grep:

tail -n +50000 myfile.txt | grep -in "time spent"

Alternatively you can use sed . sed can be used to mimic grep like this:

sed -n 's/pattern/&/p'

By default sed prints every line even if no substitution occurs. The combinations of -n and /p makes sed print only the lines where a substitution has occured. Finally, we replace pattern by & which means replace pattern by itself. Result: we just mimicked grep .

Now sed can take a range of lines on which to act. In your case:

sed -n '50000,$s/time spent/&/p' myfile.txt

The format to specify the range is as follow: start,end We just instruct sed to work from line 50000 to $ which means last line.

Answer for grepping between any 2 line numbers:

Using sed and grep:

sed -n '1,50000p' someFile | grep < your_string >

You could use head + grep and group commands with {...} so that they share the same input:

{ head -n 50000 >/dev/null; grep -i PATTERN; } < infile

head doesn't consume the whole input, it gets only the first 50000 lines and dumps them to /dev/null ; the remaining lines are processed by grep .
If you need the line numbers prepended (like with grep -in ) you could use awk :

awk 'NR>50000 && tolower($0)~/PATTERN/{print NR ": " $0}' infile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM