CodyJae
CodyJae

Reputation: 23

Splitting a list of words from a text file into an array in BASH

I've been fighting with this a lot this past hour or so, I'm trying to get a text file filled with names into an array of those words.

The text file is formated:

Word1~~Word2 Word1~~Word2

.. Eventually I want to split up these words into 2 arrays of word1 and word2 breaking at the "~~" but that is a problem for later

Right now I (currently) have this:

#!/bin/bash

a=$(cat ~/words.txt)
c=0

for word in $a
do
    arrayone[$c]=(echo $word)
    c=$((c+1))
done

I've tried many many other ways and all either don't work or error out upon execution, I'm relatively new at BASH and am having extreme difficult with the syntax

Thank you for your time

Upvotes: 0

Views: 558

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295579

It's actually just as easy to solve your "later" problem right now. Unless you need to be able to deal with words with (unpaired) literal ~ characters, this will do:

declare -a arr1=() arr2=()
while IFS='~' read -r word1 _ word2; do
  arr1+=( "$word1" )
  arr2+=( "$word2" )
done <file

printf 'Words in column 1:\n'
printf '  %s\n' "${arr1[@]}"

printf 'Words in column 2:\n'
printf '  %s\n' "${arr2[@]}"

If you do need to deal with the more interesting case, treating only a double tilde as special, one approach to doing so is with a regex match:

while IFS='' read -r line; do
  if [[ $line =~ (.*)[~][~](.*) ]]; then
    arr1+=( "${BASH_REMATCH[1]}" )
    arr2+=( "${BASH_REMATCH[2]}" )
  else
    printf 'Line does not match pattern: %s\n' "$line" >&2
  fi
done <file

Upvotes: 2

Related Questions