Add Each method to the *Scanner.
diff --git a/shell.go b/shell.go
index c787468..7f4af92 100644
--- a/shell.go
+++ b/shell.go
@@ -218,6 +218,20 @@
return s.buf
}
+// Each calls f for each token in the scanner until the input is exhausted, f
+// returns false, or an error occurs.
+func (s *Scanner) Each(f func(tok string) bool) error {
+ for s.Next() {
+ if !f(s.Text()) {
+ return nil
+ }
+ }
+ if err := s.Err(); err != io.EOF {
+ return err
+ }
+ return nil
+}
+
// Split partitions s into tokens divided on space, tab, and newline characters
// using a *Scanner. Leading and trailing whitespace are ignored.
//
diff --git a/shell_test.go b/shell_test.go
index d72c62a..3d4b55b 100644
--- a/shell_test.go
+++ b/shell_test.go
@@ -142,3 +142,18 @@
fmt.Println(string(rest))
// Output: found marker; all the remaining stuff
}
+
+func ExampleScanner_Each() {
+ const input = `a\ b 'c d' "e f's g" stop "go directly to jail"`
+ if err := NewScanner(strings.NewReader(input)).Each(func(tok string) bool {
+ fmt.Println(tok)
+ return tok != "stop"
+ }); err != nil {
+ log.Fatal(err)
+ }
+ // Output:
+ // a b
+ // c d
+ // e f's g
+ // stop
+}