1

What we want to accomplish. Have one source file (data.csv) to be referenced with the following data:

userone,password1 
usertwo,password2 
userthree,password3

Use the source file to find a username and then provide the password after the comma as another variable. Example

Variables:
User1=userone
User1Password=password1

#!/usr/bin/env bash
source data.csv
read data.csv
If $User1=userone
    then
$User1Password=password1
  • We are using this to create a local user account on a Mac with a different line of code but need to reference a .csv file to get the variables.

Thanks in advance for any support.

2 Answers 2

2

Use awk

user=userone
pass=$(awk -F, -v user="$user" '$1 == user { print $2; exit }' data.csv)

-F, sets the field separator to comma. -v user="user" sets the awk variable from the bash variable. $1 and $2 are the contents of those fields of the CSV.

Sign up to request clarification or add additional context in comments.

4 Comments

Barmar, Thank you for the quick reply. When using your script the $pass variable produces "user2" when I add echo $pass. Which is the next line item in column one. We want to print what is after the comma on the same line, i.e "password1". Do you have another suggestion? We are looking on our end. Thanks for getting us in the right direction.
I just tried it and echo $pass shows password1. I don't know why it doesn't work for you.
Make sure data.csv doesn't use CRLF as its line break. If you created the file on Windows, use dos2unix to convert it to Unix format.
You are a genius!
0
cat data.csv | \                                         # piping file contents to the loop
while read line; do                                      # reading the input stream line by line
    username=$(echo $line | awk -F',' '{print $1}')      # username is the 1st string if a , is the delimiter
    password=$(echo $line | awk -F',' '{print $2}')      # password is the 2nd string if a , is the delimiter
    echo ${username} ${password}                         # test
done

2 Comments

This should be while IFS=, read username password; do echo "$username" "$password"; done < data.csv. No pipe, no unnecessary awk processes.
You could also use cut instead of awk, it's simpler.

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.