简体   繁体   中英

Read multiple variables from file

I need to read a file that has lines like

user=username1
pass=password1

How can I read multiple lines like this into separate variables like username and password?

Would I use awk or grep? I have found ways to read lines into variables with grep but would I need to read the file for each individual item?

The end result is to use these variables to access a database via the command line. So I need to be able to read, store and use these values in other commands.

if the process which generates the file is safe and has shell syntax just source the file.

. ./file

Otherwise the file can be processes before to add quotes

perl -ne 'if (/^([A-Za-z_]\w*)=(.*)/) {$k=$1;$v=$2;$v=~s/\x27/\x27\\\x27\x27/g;print "$k=\x27$v\x27\n";}' <file >file2
. ./file2

If you want to use then

Input

$ cat file 
user=username1
pass=password1

Reading

$ user=$(awk -F= '$1=="user"{print $2;exit}' file)
$ pass=$(awk -F= '$1=="pass"{print $2;exit}' file)

Output

$ echo $user
username1
$ echo $pass
password1

file.txt :

user=username1
pass=password1
user=username2
pass=password2
user=username3
pass=password3

Do to avoid browsing several times the file file.txt :

#!/usr/bin/env bash

func () {
    echo "user:$1 pass:$2"
}

i=0
while IFS='' read -r line; do
    if [ $i -eq 0 ]; then
        i=1
        user=$(echo ${line} | cut -f2 -d'=')
    else
        i=0
        pass=$(echo ${line} | cut -f2 -d'=')
        func "$user" "$pass"
    fi
done < file.txt

Output:

user:username1 pass:password1
user:username2 pass:password2
user:username3 pass:password3

You could use a loop for your file perhaps, but this is probably the functionality you're looking for.

$ echo 'user=username1' | awk -F= '{print $2}'
username1

Using the -F flag sets the delimiter to = and we select the 2nd item from the row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM