Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 665
maniat1k13 Avatar asked Jun 07 '12 12:06

maniat1k13


People also ask

How do you read in bash?

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.


2 Answers

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" 
like image 174
Some programmer dude Avatar answered Sep 24 '22 12:09

Some programmer dude


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.

like image 30
Todd A. Jacobs Avatar answered Sep 24 '22 12:09

Todd A. Jacobs