George
George

Reputation: 25

Split two numbers in two arrays

I need to split 2 numbers in the form(they are from a text file):

Num1:Num2
Num3:Num4

And store num1 into array X and number 2 in array Y num 3 in array X and num4 in array Y.

Upvotes: 0

Views: 84

Answers (4)

grand central
grand central

Reputation: 49

Here is a quick bash solution:

c=0
while IFS=: read a b ;do
 x[$c]="$a"
 y[$c]="$b"
 c=$((c+1))
done < input.txt

We send the input.txt to a while loop, using Input Field Separator : and read the first number of each line as $a and second number as $b. Then we add them to the array as you specified. We use a counter $c to iterate the location in the arrays.

Upvotes: 1

James Brown
James Brown

Reputation: 37424

Using =~ operator to store the pair of numbers to array $BASH_REMATCH:

$ cat file
123:456
789:012
$ while read -r line
do 
    [[ $line =~ ([^:]*):(.*) ]] && echo ${BASH_REMATCH[1]} ${BASH_REMATCH[2]}
    # do something else with numbers as they will be replaced on the next iteration
done < file

Upvotes: 0

Cyrus
Cyrus

Reputation: 88774

With bash:

mapfile -t X < <(cut -d : -f 1 file) # read only first column
mapfile -t Y < <(cut -d : -f 2 file) # read only second column
declare -p X Y

Output:

declare -a X='([0]="num1" [1]="num3")'
declare -a Y='([0]="num2" [1]="num4")'

Disadvantage: The file is read twice.

Upvotes: 1

janos
janos

Reputation: 124724

You could perform the following steps:

  • Create destination arrays empty
  • Read file line by line, with a classic while read ... < file loop
  • Split each line on :, again using read
  • Append values to arrays

For example:

arr_x=()
arr_y=()
while IFS= read line || [ -n "$line" ]; do
    IFS=: read x y <<< "$line"
    arr_x+=("$x")
    arr_y+=("$y")
done < data.txt

echo "content of arr_x:"
for v in "${arr_x[@]}"; do
    echo "$v"
done

echo "content of arr_y:"
for v in "${arr_y[@]}"; do
    echo "$v"
done

Upvotes: 1

Related Questions