Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash: Assign each line in file to array; if array[n] is null then replace value

I’m stuck on a bash problem. The script should read each line in data.txt and assign it to an array before checking if each array value is empty. If the array value is empty, the text "unknown" should replace the empty value. Line 2 would otherwise have the text $Author.

data.txt

07/22/2022, 00:00:00

NASA Reveals Webb Telescope's first images of unseen universe
"We are elated to celebrate this extraordinary day with the world," said Greg Robinson, Webb program director at NASA Headquarters.
webb, telescopes, images, reveals, galaxies, star, unseen, nasa, universe, nebula, webbs, gas, view, space

bashscript.sh

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# assign each line in data.txt to array
readarray data < data.txt

# for each value in array
for i in "${data[@]}"; do

    # check if value is null
    if [ -z "$data[i]" ]; then

        # if value is null, assign text "unknown" to value
        data[i]="unknown"

    fi

done


Author=${data[1]}

echo "author: $Author"

ouput:

author:

expected output:

author: unknown

Thanks for reading/helping….

>Solution :

The main problem with your script is that a string consisting of a new-line character isn’t considered a null string. The check for the empty line should have been if [ "${data[i]}" = $'\n' ]. Also you should have used a C-style for loop. Below is a corrected version of your script:

#!/bin/bash

readarray data < data.txt

# for each value in array
for ((i = 0; i < ${#data[@]}; ++i)); do
    # check if value is null
    if [  "${data[i]}" = $'\n' ]; then

        # if value is null, assign text "unknown" to value
        data[i]="unknown"

    fi

done

Author=${data[1]}

echo "author: $Author"

Or, as suggested by glenn jackman, use the readarry with the -t flag and check for the empty string as [ -z "${data[i]}" ]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading