0

Someone please advise what it's called in bash function that reads the file and creates an array from it? Thank you

4
  • What are you trying to accomplish? Commented Mar 2, 2013 at 0:22
  • 1
    Possible duplicate of stackoverflow.com/questions/9736202/… Commented Mar 2, 2013 at 0:24
  • Reading file and creating from file array...is a direct function, but I can not find it Commented Mar 2, 2013 at 0:26
  • @jitendra: The OP is explicitly asking for a built-in, which is different from the linked question (although the built-in might have been an answer for that, it wasn't provided). Commented Mar 2, 2013 at 3:48

2 Answers 2

1

I'm currently using windows so no bash here but this is how you do it:

value=0; while read line do value=`expr $value + 1`; arr[$value]=$line; done < "myfile" 
Sign up to request clarification or add additional context in comments.

3 Comments

what makes you think exists a function that does it in bash?
alternatively: declare -a arr=($(cat myfile))
$( < myfile) is more efficient.
1

I think you're looking for the built-in mapfile.

From help mapfile:

mapfile: mapfile [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array] Read lines from the standard input into an indexed array variable. Read lines from the standard input into the indexed array variable ARRAY, or from file descriptor FD if the -u option is supplied. The variable MAPFILE is the default ARRAY. Options: -n count Copy at most COUNT lines. If COUNT is 0, all lines are copied. -O origin Begin assigning to ARRAY at index ORIGIN. The default index is 0. -s count Discard the first COUNT lines read. -t Remove a trailing newline from each line read. -u fd Read lines from file descriptor FD instead of the standard input. -C callback Evaluate CALLBACK each time QUANTUM lines are read. -c quantum Specify the number of lines read between each call to CALLBACK. Arguments: ARRAY Array variable name to use for file data. If -C is supplied without -c, the default quantum is 5000. When CALLBACK is evaluated, it is supplied the index of the next array element to be assigned and the line to be assigned to that element as additional arguments. If not supplied with an explicit origin, mapfile will clear ARRAY before assigning to it. Exit Status: Returns success unless an invalid option is given or ARRAY is readonly or not an indexed array. 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.