How can I remove blank line from input file

I want to remove blank line from my input.txt and want to store every group i.e. First line, Second line, Third line in single slice of array to calculate number of member in individual group

Input.txt
First line
First line

Second line
Second line
Second line
Second line

Third line
Third line
Third line

1 Like
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	var lines [][]string

	f, err := os.Open(`Input.txt`)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()

	s := bufio.NewScanner(f)
	newLine := true
	for s.Scan() {
		line := strings.TrimSpace(s.Text())
		if len(line) == 0 {
			newLine = true
			continue
		}
		if newLine {
			newLine = false
			lines = append(lines, make([]string, 0))
		}
		last := len(lines) - 1
		lines[last] = append(lines[last], line)
	}
	if err := s.Err(); err != nil {
		fmt.Println(err)
		return
	}

	for _, line := range lines {
		fmt.Println(len(line), ":", strings.Join(line, " || "))
	}
}

.

2 : First line || First line
4 : Second line || Second line || Second line || Second line
3 : Third line || Third line || Third line
2 Likes

Thank you

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.