`sed`: A Guide for Mere Mortals: 04
Software : GNU SED Version : 4.2.1 Compatibility : Any Copy of Sed
In the previous “Guide for Mere Mortals” we started to delve into some of the “Additional” Functionality sed possesses outside of simple substitution.
This time I’m going to focus on a very very VERY specific use case of sed, that will help start to build a more vast comprehension of how the magic of sed really starts to fit together.
This use case involves the idea of chaining multiple sed elements together using the curly brackets!
{}
The specific use case I have in mind is pulling in multiple lines of text after the pattern, and performing an action on it. For example, say you have a log file that collects a lot of relevant information, but it’s filled with random entries about yams for some reason:
Intrusion: Yams 12/13/2014 purple orange green Intrusion: Yams 12/14/2014 purple orange green Intrusion: Yams 12/16/2014 purple orange green Intrusion: CRACKERS! 12/15/2014 Bad ones The did stuff Heres the info Intrusion: Yams 12/16/2014 purple orange green
So lets say you’ve got hundreds of lines that look like this. And amongst the multitude of yam information, you have a few good bits… Rather than sorting through these manually, you can chain together some sed magic fairly easily… For example using the “N” function of sed which pulls the next line of information after the pattern into the pattern, as well as the “d” function which deletes the pattern:
sed '/Yam/ {N;N;N; d;}' log1.log
So, This sed script will look for the pattern “Yam”, then it will read in the next 3 lines, IE “Purple, orange, and Green”, and then delete the pattern, leaving you with:
Intrusion: CRACKERS! 12/15/2014 Bad ones The did stuff Heres the info
Again, this is a very specific use case, but also very helpful. That is all for this installment. Stay on your seat for episode 5: The Sedpire strikes Back.