rrfeva
rrfeva

Reputation: 87

Concatenating a string from an array

I have a full names that have been read into arrays. I am trying to create a file using only the last name; the last name might have white spaces that should be replaced by underscores. My thought is to create a string of the file name and then create the file. I have already taken care of the cases with only one last name. I am having trouble with the last names with white spaces. This is what I have so far:

if [ "${#name_arr[@]}" -eq 2 ]; then
    for i in "${name_arr[@]:1}";do  # :1 because first element is their first name
        last_name=$i
    done
    echo $last_name
else
    for i in "${name_arr[@]:1}";do
        last_name=${last_name}_${i}
    done
    echo $last_name
fi

The output of this concatenates all of the names with underscores. So instead of:

Doe
Austen
Vaughn_Williams
Doe

It is echoing:

Doe
Austen
Austen_Vaughn_Williams
Doe

Upvotes: 0

Views: 82

Answers (2)

chepner
chepner

Reputation: 531055

You don't need loops, or nor do you need to check the length of the list. Just join all but the first element with a space to get the last name.

last_name=${name_arr[*]:1}  # Assuming the default value of IFS
last_name=${last_name// /_}

At the cost of a fork, you can do this in one line.

last_name=$(IFS='_'; echo "${name_arr[*]:1}")

Upvotes: 2

BlackPearl
BlackPearl

Reputation: 1662

Try this approach

if [ "${#name_arr[@]}" -eq 2 ]; then
    for i in "${name_arr[@]:1}";do  # :1 because first element is their first name
        last_name=$i
    done
    echo $last_name
else
    last_name=${name_arr[1]}
    for i in "${name_arr[@]:2}";do
        last_name=${last_name}_${i}
    done
    echo $last_name
fi

First, take the 2nd element of the name_arr in the last_name, and add the remaining elements of the array in to the last_name variable with a loop

Upvotes: 0

Related Questions