How to process a file line by line in Go?

In the Go programming language, How to process a file line by line?

An equivalent piece of Bash code could be

while read line ; do
    echo $line
done < ./input.txt

You can make use of the bufio package’s Scan().

// open the file filepath
f := os.Open(filepath)
// create a scanner
fs := bufio.NewScanner(f)

// scan file https://golang.org/pkg/bufio/#Scanner.Scan
for fs.Scan() {
        txt := fs.Text()
        // do anything with txt
}

If you are reading line by line from STDIN:

fs := bufio.NewScanner(os.Stdin)
for fs.Scan() {
    txt := fs.Text()
    // process txt
}

Similar Posts

  • |

    Linux Kernel: cifs: release auth_key.response for reconnect

    This change “cifs: release auth_key.response for reconnect.” (commit f5c4ba8) in Linux kernel is authored by Shu Wang <shuwang [at] redhat.com> on Fri Sep 8 18:48:33 2017 +0800. Description of “cifs: release auth_key.response for reconnect.” The change “cifs: release auth_key.response for reconnect.” introduces changes as follows. cifs: release auth_key.response for reconnect. There is a race that…

  • |

    Synchronizing home directories

    Any good tools to synchronize home directories on Linux boxes? Many have several PC/laptops and consequently many home directories. There is home directory synchronizing problem. unison is a good tool to do this: http://www.cis.upenn.edu/~bcpierce/unison/download/releases/stable/unison-manual.html#rshmeth http://www.watzmann.net/blog/2009/02/my-homedirs-in-unison.html http://www.cis.upenn.edu/~bcpierce/papers/index.shtml#File%20Synchronization Useful script: $ unison -batch -ui text ./ /mnt/homebak/zma/ In text user interface, synchronizing two directories in batch mode…

  • How to install PARSEC correctly.

    PARSEC is the most important CPU-bound benchmark for systems. It is huge and hard to install because it needs lots of 3-part libs. PARSEC download link for 3.0 version: http://parsec.cs.princeton.edu/download.htm#parsec I remembered I added the answer yesterday night but I could not see the answer currently. Anyway, let me add the answer again after I…

  • How to use ioprio_set in linux c

    Since there is no glibc wrapper for ioprio_set in linux c, we need to call this API with some definition. Using syscall in linux as follows. syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, pid, IOPRIO_PRIO_CLASS(IOPRIO_CLASS_IDLE)); Some other definitions to declare above macros. 69 enum { 70 IOPRIO_CLASS_NONE, 71 IOPRIO_CLASS_RT, 72 IOPRIO_CLASS_BE, 73 IOPRIO_CLASS_IDLE, 74 }; 75 76 enum { 77…

Leave a Reply

Your email address will not be published. Required fields are marked *