-1

Im using a function that gives me 300 000 lines that look like this :

XXXXXXXXX 
WWWWWWWWWWWW

ZZZZZZZZZZ

eeeeeeeeeee

and i want to get something like this in an array

tab[0]=XXXXXXXXX tab[1]= tab[1]= WWWWWWWWWWWW tab[1]= none 

I tried this :

#!/bin/bash
for i in text.txt
do
   tab=[i]
done
Barmar
  • 741,623
  • 53
  • 500
  • 612
akmot
  • 63
  • 8
  • 2
    Please take a look at [How do I format my posts using Markdown or HTML?](https://stackoverflow.com/help/formatting). – Cyrus Jul 12 '22 at 16:28
  • Could you please also format your example data as it were code? Otherwise symbols could be misplaced or misinterpreted. – mashuptwice Jul 12 '22 at 16:29
  • Does this answer your question? [Looping through the content of a file in Bash](https://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash) – mashuptwice Jul 12 '22 at 16:30
  • Why do you have 3 different values for `tab[1]`? Did you mean `tab[2]` and `tab[3]`? – Barmar Jul 12 '22 at 16:39
  • I don't see how your desired result is related to the sample file. – Barmar Jul 12 '22 at 16:40

3 Answers3

0

Use a while read loop to read the file line by line, and append the line to the tab array.

tab=()
while read -r line; do
    tab+=("${line:-none}")
done < filename

:-default in a variable expansion means to use default if the variable is empty, so empty lines will be replaced with none in the array.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Use mapfile to map lines of text to an array:

mapfile -t tab < text.txt
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
0
$ readarray -t tab <file
$ declare -p tab
declare -a tab=([0]="XXXXXXXXX " [1]="WWWWWWWWWWWW" [2]="" [3]="ZZZZZZZZZZ" [4]="" [5]="eeeeeeeeeee")

# adding none
$ readarray -t tab < <(awk '{print ($0=="" ? "none" : $0)}' file)
$ declare -p tab
declare -a tab=([0]="XXXXXXXXX" [1]="WWWWWWWWWWWW" [2]="none" [3]="ZZZZZZZZZZ" [4]="none" [5]="eeeeeeeeeee")

# associative array
$ declare -A arr="($(awk '{print ($0=="" ? "[tab,"NR"]=\"none\"" : "[tab,"NR"]=\""$0"\"")}' file))"
$ declare -p arr
declare -A arr=([tab,6]="eeeeeeeeeee" [tab,4]="ZZZZZZZZZZ" [tab,5]="none" [tab,2]="WWWWWWWWWWWW" [tab,3]="none" [tab,1]="XXXXXXXXX" )
ufopilot
  • 3,269
  • 2
  • 10
  • 12