0

I have a text file which consists of say ..following information say test.text:

an
apple of 
one's eye

I want to read these lines in an array using shell scripting by doing a cat test.text. I have tried using a=(`cat test.text`), but that doesn't work as it considers space as a delimiter. I need the values as a[0]=an , a[1]=apple of , a[2]=one's eye. I don't want to use IFS. Need help, thanks in advance..!!

4 Answers 4

2

In bash 4 or later

readarray a < test.text

This will include an empty element for each blank line, so you might want to remove the empty lines from the input file first.

In earlier versions, you'll need to build the array manually.

a=()
while read; do a+=("$REPLY"); done < test.text
1

One of various options you have is to use read with . Set IFS to the newline and line separator to NUL

IFS=$'\n' read -d $'\0' -a a < test.txt
4
  • $'\0' is effectively equivalent to '' (variables are C strings internally)
    – Jo So
    Commented Nov 8, 2013 at 17:23
  • @JoSo, good point. I tend to use $'\0' for consistency with $'\n'
    – iruvar
    Commented Nov 8, 2013 at 17:33
  • You're right, that's at least visually more consistent. The downside is that it hides the fact that the shell can't store NULs in variables. The read-NUL-delimited feature in bash is maybe not even intentional but stemming from the fact that the algorithm is "The first character of delim is used to terminate the input line, rather than newline.", and what happens if the argument is the empty string is not further specified. The implementation simply dereferences the C string corresponding to the variable, yielding the NUL terminator in case of an empty string.
    – Jo So
    Commented Nov 8, 2013 at 17:49
  • (see stackoverflow.com/questions/11855406/… )
    – Jo So
    Commented Nov 8, 2013 at 17:50
1

Plain sh

IFS='
'
set -- $(< test.txt)
unset IFS
echo "$1"
echo "$2"
echo "$@"

bash

IFS=$'\n' a=($(< test.txt))
echo "${a[0]}"
echo "${a[1]}"
echo "${a[@]}"

I'm inclined to say these are the best of the available solutions because they do not involve looping.

0

Let's say:

cat file
an

apple of

one's eye

Use this while loop:

arr=()
while read -r l; do
    [[ -n "$l" ]] && arr+=("$l")
done < file

TEST

set | grep arr
arr=([0]="an" [1]="apple of" [2]="one's eye")

Not the answer you're looking for? Browse other questions tagged or ask your own question.