I am trying to create arrays from strings that have a separator ("|") as separators and include spaces. For a while I looked around, and thanks to sources such as How do I split a line on a delimiter in Bash? , Splitting a string into an array and a bunch more. I'm close, but it doesn’t quite work. The two main problems are that there are spaces in the lines, there are start and end separators, and some fields are blank. Also, instead of just displaying the values, I need to assign them to the variables. Here is the source data format:
|username|full name|phone1|phone2|date added|servers|comments|
Example:
|jdoe | John Doe| 555-1212 | |1/1/11 | workstation1, server1 | added by me |
This is what I need:
Username: jdoe Fullname: John Doe Phone1: 555-1212 Phone2: Date_added: 1/1/11 Servers: workstation1, server1 Comments: guest account
Change: I use sed to remove the first and last separator and spaces before and after each separator, now input:
jdoe|John Doe|555-1212||1/1/11|workstation1, server1|added by me
Here is what I tried:
oIFS="$IFS"; IFS='|' for line in 'cat $userList'; do arr=("$line") echo "Username: ${arr[0]}"
Output:
Username: Full Name: Phone 1: Phone 2: Username: jdoe Full Name: Phone 1: Phone 2: Username: John Doe Full Name: Phone 1: Phone 2:
One more thing I tried:
for line in 'cat $userList'; do arr=(${line//|/ }) echo "Username: ${arr[0]}" echo "Full Name: ${arr[1]}" echo "Phone 1: ${arr[2]}" echo "Phone 2: ${arr[3]}"
Output:
Username: jdoe Full Name: John Phone 1: Phone 2: Username: Doe Full Name: 555-1212 Phone 1: Phone 2:
Do you have some ideas? Thanks!!
source share