2015-09-22 08:25:10 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"flag"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strconv"
|
|
|
|
|
2016-04-28 18:29:58 +00:00
|
|
|
"github.com/kisom/goutils/die"
|
2015-09-22 08:25:10 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func usage() {
|
|
|
|
progname := filepath.Base(os.Args[0])
|
2015-11-25 23:01:13 +00:00
|
|
|
fmt.Printf(`Usage: %s [-nl] file start [end]
|
2015-09-22 08:25:10 +00:00
|
|
|
|
|
|
|
Print a fragment of a file starting a line 'start' and ending
|
|
|
|
at line 'end', or EOF if no end is specified.
|
2015-11-25 23:01:13 +00:00
|
|
|
|
|
|
|
The -nl flag will suppress printing of line numbers.
|
2015-09-22 08:25:10 +00:00
|
|
|
`, progname)
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2015-11-25 23:01:13 +00:00
|
|
|
quiet := flag.Bool("nl", false, "No line-numbering.")
|
2015-09-22 08:25:10 +00:00
|
|
|
flag.Parse()
|
|
|
|
|
|
|
|
if flag.NArg() < 2 || flag.NArg() > 3 {
|
|
|
|
usage()
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
start, err := strconv.Atoi(flag.Arg(1))
|
|
|
|
die.If(err)
|
|
|
|
|
|
|
|
var end int
|
|
|
|
var offset bool
|
|
|
|
if flag.NArg() == 3 {
|
|
|
|
endStr := flag.Arg(2)
|
|
|
|
if endStr[0] == '+' {
|
|
|
|
offset = true
|
|
|
|
endStr = endStr[1:]
|
|
|
|
}
|
|
|
|
end, err = strconv.Atoi(endStr)
|
|
|
|
die.If(err)
|
|
|
|
if offset {
|
|
|
|
end += start
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
file, err := os.Open(flag.Arg(0))
|
|
|
|
die.If(err)
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
|
|
|
|
|
|
// initial empty line to start numbering at 1.
|
|
|
|
var lines = make([]string, 1)
|
|
|
|
for scanner.Scan() {
|
|
|
|
lines = append(lines, scanner.Text())
|
|
|
|
}
|
|
|
|
|
2015-09-22 08:46:54 +00:00
|
|
|
if end == 0 {
|
|
|
|
end = len(lines) - 1
|
|
|
|
}
|
|
|
|
|
|
|
|
if end < start {
|
2015-10-28 23:31:14 +00:00
|
|
|
fmt.Fprintln(os.Stderr, "[!] end < start, swapping values")
|
2015-09-22 08:46:54 +00:00
|
|
|
tmp := end
|
|
|
|
end = start
|
|
|
|
start = tmp
|
|
|
|
}
|
|
|
|
|
2015-11-25 23:01:13 +00:00
|
|
|
var fmtStr string
|
|
|
|
|
|
|
|
if !*quiet {
|
|
|
|
maxLine := fmt.Sprintf("%d", len(lines))
|
|
|
|
fmtStr = fmt.Sprintf("%%0%dd: %%s", len(maxLine))
|
|
|
|
}
|
2015-09-22 08:25:10 +00:00
|
|
|
|
|
|
|
endFunc := func(n int) bool {
|
|
|
|
if n == 0 {
|
|
|
|
return false
|
|
|
|
}
|
2015-09-22 08:46:54 +00:00
|
|
|
|
2015-09-22 08:25:10 +00:00
|
|
|
if n > end {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
fmtStr += "\n"
|
|
|
|
for i := start; !endFunc(i); i++ {
|
2015-11-25 23:01:13 +00:00
|
|
|
if *quiet {
|
|
|
|
fmt.Println(lines[i])
|
|
|
|
} else {
|
|
|
|
fmt.Printf(fmtStr, i, lines[i])
|
|
|
|
}
|
2015-09-22 08:25:10 +00:00
|
|
|
}
|
|
|
|
}
|