magesh
magesh

Reputation: 39

How to assign each line in a text to an array in shell scripting?

I have a text file named "raj.txt" containing following content:


raj magesh popey ravi


How can I assign each word to array element? a[0]=raj a[1]=magesh a[2]=popey a[3]=ravi

Upvotes: 1

Views: 57

Answers (2)

ghostdog74
ghostdog74

Reputation: 342977

Try bash:

while IFS= read -r line
do
   set -- $line
   echo "$1"
   echo "$2"
done < file

Upvotes: 1

cuonglm
cuonglm

Reputation: 2816

If your shell support array, like bash, zsh, ksh93, try:

$ array=($(<filename))
$ printf '%s\n' "${array[0]}"
raj
$ printf '%s\n' "${array[1]}"
magesh
$ printf '%s\n' "${array[2]}"
popey
$ printf '%s\n' "${array[3]}"
ravi

Upvotes: 0

Related Questions