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
CodePudding user response:
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.
CodePudding user response:
Use mapfile
to map lines of text to an array:
mapfile -t tab < text.txt
CodePudding user response:
$ 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" )