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/tail/main.go

47 lines
771 B

package main
import (
"fmt"
"bufio"
"os"
"log"
"flag"
"io"
)
func TailFile(file io.Reader, count int) {
scan := bufio.NewScanner(file)
var lines []string
for scan.Scan() {
lines = append(lines, scan.Text())
}
if scan.Err() != nil { log.Fatal(scan.Err()) }
start := len(lines) - count
if start < 0 { start = 0 }
for line := int(start); line < len(lines); line++ {
fmt.Println(lines[line])
}
}
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) }
TailFile(file, count)
}
} else {
TailFile(os.Stdin, count)
}
}