Golang : Display a text file line by line with line number example
Problem:
Instead of using cat
or more
commands to display a text file line by line. You want to display the file content line by line with a number for each line in a terminal. You also want to know how many total lines are there in the text file. How to do that?
Solution:
Use this simple Golang program to display the text file content with line number on the right side.
countdisplaylines.go
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
if len(os.Args) <= 1 {
fmt.Printf("USAGE : %s <target_filename> \n", os.Args[0])
os.Exit(0)
}
fileName := os.Args[1]
fileBytes, err := ioutil.ReadFile(fileName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lines := strings.Split(string(fileBytes), "\n")
// remove the last item from the lines slice
// which is empty
lines = lines[:len(lines)-1]
// len() function will count the total number of lines
fmt.Println(fileName, "has a total of", len(lines), "lines")
for i, line := range lines {
// i = i + 1 // uncomment to start from 1 instead of 0
fmt.Println(i, line)
}
}
Sample output:
$ ./countdisplaylines 123.txt
123.txt has a total of 3 lines
0 one
1 two
2 three
content of the
123.txt
file:one
two
three
See also : Golang : Write multiple lines or divide string into multiple lines
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.1k Android Studio : Image button and button example
+11.8k Golang : Concurrency and goroutine example
+15.4k JavaScript/JQuery : Detect or intercept enter key pressed example
+11.6k Golang : Handle API query by curl with Gorilla Queries example
+22.2k Golang : Use TLS version 1.2 and enforce server security configuration over client
+7.7k Golang : Rot13 and Rot5 algorithms example
+11.9k Golang : Secure file deletion with wipe example
+23.3k Golang : Randomly pick an item from a slice/array example
+14.2k Golang : Human readable time elapsed format such as 5 days ago
+7.2k Golang : How to setup a disk space used monitoring service with Telegram bot
+13k Swift : Convert (cast) Int or int32 value to CGFloat
+22.1k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload