4

i have parsed a file using catand now I want to save the result of it in array.

var1=$(cat abc.txt | grep .........)

and the var1 looks like

33 23 51 11 16 43 5 50 4 2 12 29 32 28 47 41 7 20 38 45 49 26 22 10 44 9 19 27 46

1.I want each value to be stored as array variables but when I do this all result of 'cat is stored at index 0 of var1

How to save each value as different index?

  • There are several ways to produce an array. One of them is var_arr=( $(grep … abc.txt) ) – Costas Oct 20 '15 at 6:45
  • Second is to use special command like read -a, readlines|mapfile – Costas Oct 20 '15 at 6:48
  • Third — add to array in a loop: for m in $var1 ; do var_arr[${#var_arr[*]}]=m ; done – Costas Oct 20 '15 at 6:50
  • @Costas, I have tried the Third way to but that is not working, if I use it and then to check if I check echo ${var_arr[0]}then i see m although if i add echo $m tiger u see that m is a number. – Umar Oct 20 '15 at 8:10
  • Sorry, I have miss $ mark. Should be var_arr[${#var_arr[*]}]=$m – Costas Oct 20 '15 at 8:27
3

In bash the readarray builtin can store the values in arrays:

readarray arr < <(grep "pattern" abc.txt)

This will create an array called arr with the values given by the command grep "pattern" abc.txt (if they come in multiple lines, readarray appends them to the array):

echo ${arr[0]}
33
$ echo ${arr[10]}
12
$ echo ${arr[*]}
33 23 51 11 16 43 5 50 4 2 12 29 32 28 47 41 7 20 38 45 49 26 22 10 44 9 19 27 46

BTW: cat file | grep ... can be shortened to grep ... file, grep can also read files.

| improve this answer | |
  • read puts into array 1 line (before first \newline) only – Costas Oct 20 '15 at 6:53
  • @Costas Isn't that what the user wants? – chaos Oct 20 '15 at 6:54
  • Suppose grep produce multiline output. In the case there is suitable echoing: read -a arr < <(echo $(grep "pattern" abc.txt)) – Costas Oct 20 '15 at 6:54
  • @Costas now it supports multiline input. – chaos Oct 20 '15 at 7:00
  • @chaos, I am using Mac OS and when i enter readarray arr < <(grep "pattern" abc.txt) the bash shell becomes super slow .. and if i close the shell then every things gets back to normal.. any idea why this is happening – Umar Oct 20 '15 at 7:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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