Pol Hallen
Pol Hallen

Reputation: 1862

Parsing text file to variables

$ cat file.txt
example1@domain1-username

I'd like to parse file.txt and export the contents to variables like:

var1=example1@domain1
var2=username

Upvotes: 1

Views: 251

Answers (3)

watchmansky
watchmansky

Reputation: 190

var1=$(cut -d "-" -f 1 file.txt)

var2=$(cut -d "-" -f 2 file.txt)

Upvotes: 1

Benjamin W.
Benjamin W.

Reputation: 52102

Using just Bash builtins:

$ IFS=- read var1 var2 <<< "$(< file.txt)"    
$ declare -p var1 var2                      
declare -- var1="example1@domain1"                        
declare -- var2="username"

This sets the field separator IFS to -, then reads the file into the two variables.

<<< "$(< file.txt)" is a but unwieldy, as we're treating the file just like the single line of text that it is.

Upvotes: 2

gromi08
gromi08

Reputation: 515

The following command will set var1 and var2 in a single pass over file.txt:

. file.txt

Upvotes: 0

Related Questions