I've read this question about how to read n characters from a text file using bash. I would like to know how to read a word at a time from a file that looks like:
example text example1 text1 example2 text2 example3 text3
Can anyone explain that to me, or show me an easy example? Thanks!
Bash read Built-in The general syntax of the read built-in takes the following form: read [options] [name...] To illustrate how the command works, open your terminal, type read var1 var2 , and hit “Enter”. The command will wait for the user to enter the input.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With