Skip to content

Commit 7fa1e68

Browse files
committed
Implemented MatchRegexpWithLineNumber() and MatchWithLineNumber()
These behave as `grep -n` does: output the matched line prefixed by the line number.
1 parent d4778d8 commit 7fa1e68

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

script.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,20 @@ func (p *Pipe) FilterScan(filter func(string, io.Writer)) *Pipe {
512512
})
513513
}
514514

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+
515529
// First produces only the first n lines of the pipe's contents, or all the
516530
// lines if there are less than n. If n is zero or negative, there is no output
517531
// at all.
@@ -684,6 +698,16 @@ func (p *Pipe) Match(s string) *Pipe {
684698
})
685699
}
686700

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+
687711
// MatchRegexp produces only the input lines that match the compiled regexp re.
688712
func (p *Pipe) MatchRegexp(re *regexp.Regexp) *Pipe {
689713
return p.FilterScan(func(line string, w io.Writer) {
@@ -693,6 +717,16 @@ func (p *Pipe) MatchRegexp(re *regexp.Regexp) *Pipe {
693717
})
694718
}
695719

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+
696730
// Post makes an HTTP POST request to url, using the contents of the pipe as
697731
// the request body, and produces the server's response. See [Pipe.Do] for how
698732
// the HTTP response status is interpreted.

0 commit comments

Comments
 (0)