This is an education project that attempts to reimplement the GNU coreutils in Go. You can find the full manual here: https://www.gnu.org/software/coreutils/manual/coreutils.html
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
go-coreutils/head/main.go

43 lines
671 B

package main
import (
"fmt"
"bufio"
"os"
"log"
"flag"
"io"
)
func HeadFile(file io.Reader, count int) {
scan := bufio.NewScanner(file)
for cur_line := 0; scan.Scan(); cur_line++ {
line := scan.Text()
if cur_line < count {
fmt.Println(line)
}
}
if scan.Err() != nil { log.Fatal(scan.Err()) }
}
func main() {
var count int
flag.IntVar(&count, "n", 10, "number of lines")
flag.Parse()
if flag.NArg() > 0 {
files := flag.Args()
for _, fname := range files {
file, err := os.Open(fname)
if err != nil { log.Fatal(err) }
HeadFile(file, count)
}
} else {
HeadFile(os.Stdin, count)
}
}