@@ -512,6 +512,20 @@ func (p *Pipe) FilterScan(filter func(string, io.Writer)) *Pipe {
512
512
})
513
513
}
514
514
515
+ // FilterScanTrackLine behaves the same way as FilterScan() but also returns the
516
+ // line number of the processed input
517
+ func (p * Pipe ) FilterScanTrackLine (filter func (string , io.Writer , int )) * Pipe {
518
+ return p .Filter (func (r io.Reader , w io.Writer ) error {
519
+ scanner := newScanner (r )
520
+ line := 1
521
+ for scanner .Scan () {
522
+ filter (scanner .Text (), w , line )
523
+ line ++
524
+ }
525
+ return scanner .Err ()
526
+ })
527
+ }
528
+
515
529
// First produces only the first n lines of the pipe's contents, or all the
516
530
// lines if there are less than n. If n is zero or negative, there is no output
517
531
// at all.
@@ -684,6 +698,16 @@ func (p *Pipe) Match(s string) *Pipe {
684
698
})
685
699
}
686
700
701
+ // MatchWithLineNumber behaves the same way as Match() but concatenates the
702
+ // line number the pattern was found in (similar to `grep -n`)
703
+ func (p * Pipe ) MatchWithLineNumber (s string ) * Pipe {
704
+ return p .FilterScanTrackLine (func (line string , w io.Writer , lineNumber int ) {
705
+ if strings .Contains (line , s ) {
706
+ fmt .Fprintln (w , fmt .Sprint (lineNumber )+ ":" + line )
707
+ }
708
+ })
709
+ }
710
+
687
711
// MatchRegexp produces only the input lines that match the compiled regexp re.
688
712
func (p * Pipe ) MatchRegexp (re * regexp.Regexp ) * Pipe {
689
713
return p .FilterScan (func (line string , w io.Writer ) {
@@ -693,6 +717,16 @@ func (p *Pipe) MatchRegexp(re *regexp.Regexp) *Pipe {
693
717
})
694
718
}
695
719
720
+ // MatchRegexpWithLineNumber behaves the same way as MatchRegexp but concatenates the
721
+ // line number the pattern was found in (similar to `grep -n`)
722
+ func (p * Pipe ) MatchRegexpWithLineNumber (re * regexp.Regexp ) * Pipe {
723
+ return p .FilterScanTrackLine (func (line string , w io.Writer , lineNumber int ) {
724
+ if re .MatchString (line ) {
725
+ fmt .Fprintln (w , fmt .Sprint (lineNumber )+ ":" + line )
726
+ }
727
+ })
728
+ }
729
+
696
730
// Post makes an HTTP POST request to url, using the contents of the pipe as
697
731
// the request body, and produces the server's response. See [Pipe.Do] for how
698
732
// the HTTP response status is interpreted.
0 commit comments