1
$ 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
0

3 Answers 3

2

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.

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

Comments

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

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

Comments

0

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

. file.txt

1 Comment

I think the second example is what OP wants, not what they have.

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.