How can I read words (instead of lines) from a file?

The way to do this with standard input is by passing the -a flag to read:

read -a words
echo "${words[@]}"

This will read your entire line into an indexed array variable, in this case named words. You can then perform any array operations you like on words with shell parameter expansions.

For file-oriented operations, current versions of Bash also support the mapfile built-in. For example:

mapfile < /etc/passwd
echo ${MAPFILE[0]}

Either way, arrays are the way to go. It's worth your time to familiarize yourself with Bash array syntax to make the most of this feature.


The read command by default reads whole lines. So the solution is probably to read the whole line and then split it on whitespace with e.g. for:

#!/bin/sh

while read line; do
    for word in $line; do
        echo "word = '$word'"
    done
done <"myfile.txt"

Tags:

Bash