Unix & Linux
bash text-processing array for read
Updated Fri, 17 Jun 2022 07:58:16 GMT

Reading multiple files and operating on stored Arrays


I have 2 text files "${LinkP}" and "${QuestionP}. I want to read these files and store each complete line in the respective array,

IFS=$'\r\n' GLOBIGNORE='*' command eval "LinkA=($(cat "${LinkP}"))"
IFS=$'\r\n' GLOBIGNORE='*' command eval "QuestionA=($(cat "${QuestionP}"))"

Now I want to operate on these using a for loop

nLink=${#LinkA[@]} # Size of array
for ((i = 0; i < nLink; i = i + 1)); do
    echo $i
    Question=${QuestionA[i]}
    echo "Question=${QuestionA[i]}"
done

But, the Question variable doesn't contains full line, it breaks after each space character.

How can I store each question and link (complete line in respective file) in these variable and process them inside for loop.




Solution

store each complete line in the respective array

is easy with a different approach:

mapfile LinkA < "$LinkP"

See help mapfile for more options, such as -t to remove a trailing delimiter from each line.