print nth line after the line which matches the string
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
What I want is to print the third line (which should be 666666) after the line where aaa was found. I mean, I need to first search through the file to find a line includes string "aaa", then print out the third (or nth) line 666666 after this line.
The issue with your awks is you can see in the past (ie what you have stored in the array), but you cannot see into the future (ie NR +3 has yet to be stored).
The delete will trim the array, so it'll ever only contain the to-be-printed record numbers. It's a good idea if you happen to process files with many occurrences, but basically it's just an optimization.
If you have multiple trigger patterns, you could even do
Thanks everyone! Your kind and excellent answers expand this small question to a big tank of knowledge and skills. I am glad to see that we share our knowledge so broadly. This is why I join this forum and I hope every one got her progress through the communication.
I, myself, also found another way to solve this problem from a similar problem in another forum:
Code:
grep -A 3 aaa FILENAME | sed -n '4~5p'
Anybody know the meaning of '4~5p'?
Let's keep this question unsolved for a bit while, since I still have some questions on your replies. I will put my questions later on. Please wait for a bit...
Second, did you look in the sed man page? It explains what that pattern means.
But I'd use A1,+N instead, since you want a fixed number of lines after the match, rather than a step.
So use one address range to grab that section of lines, then apply a second nested command to it to print just the line you want.
Code:
sed -n '/aaa/,+3 { 1,+2d ; p }' file.txt
I don't know why, but the nested address matching is kind of tricky. I can't get it to just directly print the last line of the initial match ($ still seems to mean the last line of the file), so you have to tell it to delete everything before it instead.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.