I have a file:
header trigger text1 text2 trigger text5 trigger ... trigger ...
I want sed to only match between the first two occurrences of 'trigger'. So I tried:
sed -n '/trigger/,/trigger/p'
But as the man page for sed says, that matches all occurrences within two lines with 'trigger'. I want sed to quit after the first match, so the output would be:
trigger text1 text2 trigger
How do I accomplish this?
(quit) Exit sed without processing any more commands or input. (quit) This command is the same as q , but will not print the contents of pattern space. Like q , it provides the ability to return an exit code to the caller.
By default, the sed command replaces the first occurrence of the pattern in each line and it won't replace the second, third… occurrence in the line.
r is used to read a file and append it at the current point. The point in your example is the address /EOF/ which means this script will find the line containing EOF and then append the file specified by $thingToAdd after that point. Then it will process the rest of the file.
You can do this with a loop in GNU sed
:
sed -n '/trigger/{p; :loop n; p; /trigger/q; b loop}'
Explanation:
/trigger/
, start a block of commandsp
-- print the line:loop
-- set a label named loop
n
-- get the next linep
-- print the line/trigger/q
-- if the line matches /trigger/
then exit sed
b
-- jump to loop
While jason's ans is what you're looking for, I would have preferred using awk
for this task
awk '/trigger/{p++} p==2{print; exit} p>=1' file
Output:
trigger text1 text2 trigger
This would provide more flexibility to chose lines between n
th and m
the occurrence of trigger
.
E.g.
$ awk -v n=2 -v m=3 '/trigger/{p++} p==m{print; exit} p>=n' file trigger text5 trigger
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With