Golang : Skip or discard items of non-interest when iterating example
Problem:
You want to skip or discard items of non-interest when iterating. For example, skipping the commented lines with #
sign in the /etc/passwd
file.
##
# User Database
#
# Note that this file is consulted directly only when the system is running
# in single-user mode. At other times this information is provided by
# Open Directory.
#
# See the opendirectoryd(8) man page for additional information about
# Open Directory.
##
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false
Solution:
Test each line(item) with strings.Index()
function to see if the line starts with #
sign. If the #
sign is detected, skip or discard the item. This example reads the iterable items from a file; however, you can easily modify it to accommodates array or slice.
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func main() {
file, err := os.Open("/etc/passwd")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
line, err := reader.ReadString('\n')
// skip all line starting with #
if equal := strings.Index(line, "#"); equal < 0 {
fmt.Print(line)
}
// alternatively, only print line starting with #
//if equal := strings.Index(line, "#"); equal >= 0 {
// fmt.Print(line)
// }
if err == io.EOF {
break
}
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
}
Output:
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false
References:
https://www.socketloop.com/tutorials/golang-read-data-from-config-file-and-assign-to-variables
See also : Golang : Read data from config file and assign to variables
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
+4.8k Golang : Convert lines of string into list for delete and insert operation
+7.9k Golang : Add build version and other information in executables
+10.7k Golang : Simple image viewer with Go-GTK
+7.6k Javascript : Put image into Chrome browser's console
+30.1k Golang : How to redirect to new page with net/http?
+11.1k Android Studio : Create custom icons for your application example
+11k Golang : How to use if, eq and print properly in html template
+11.4k Golang : Surveillance with web camera and OpenCV
+10.4k Golang : Underscore string example
+5.2k Golang : fmt.Println prints out empty data from struct
+31.1k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+21.3k SSL : How to check if current certificate is sha1 or sha2