0

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
4
  • 1
    Do you mean if [ "${#name_arr[@]}" -eq 2 ] (note the #)? Commented Apr 17, 2019 at 16:32
  • @tripleee yes, sorry, that was a typo. Just fixed. Commented Apr 17, 2019 at 16:36
  • The actual output would be _Vaughn_Williams and not Austen_Vaughn_Williams. It will start with an '_' based on your code. Are you sure you are posting the correct output? Commented Apr 17, 2019 at 16:36
  • Yes, that is what my output is showing. No underscore before. Edit: If I change the variable for last name to long_last_name, then it does output _Vaughn_Williams. Commented Apr 17, 2019 at 16:39

2 Answers 2

2

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}")
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.