2

First of all, let me state that I am very new to Bash scripting. I have tried to look for solutions for my problem, but couldn't find any that worked for me.
Let's assume I want to use bash to parse a file that looks like the following:

variable1 = value1
variable2 = value2

I split the file line by line using the following code:

cat /path/to/my.file | while read line; do
    echo $line      
done

From the $line variable I want to create an array that I want to split using = as a delimiter, so that I will be able to get the variable names and values from the array like so:

$array[0] #variable1
$array[1] #value1

What would be the best way to do this?

2 Answers 2

5

Set IFS to '=' in order to split the string on the = sign in your lines, i.e.:

cat file | while IFS='=' read key value; do
    ${array[0]}="$key"
    ${array[1]}="$value"
done

You may also be able to use the -a argument to specify an array to write into, i.e.:

cat file | while IFS='=' read -a array; do
    ...
done

bash version depending.

Old completely wrong answer for posterity:

Add the argument -d = to your read statement. Then you can do:

cat file | while read -d = key value; do
    $array[0]="$key"
    $array[1]="$value"
done
Sign up to request clarification or add additional context in comments.

4 Comments

adding the -d argument gives me read: Illegal option -d, is the -d argument used for another command that i can use to do this?
Heh, actually got it wrong, -d should be the line terminator. The environment variable IFS controls splitting. Not sure why your read doesn't support -d.
Using -d with read is not POSIX compliant, unfortunately.
be aware that this something | while IFS=... read variable ; do ... ; done will redefine 'variable' only during the do ... done loop, and outside of it it's left unchanged (why? because, in bash, almost everything after a | (pipe) is done in a subshell. And a subshell inherits global variables, but the calling shell doesn't inherit their new values and keep the old ones. Usually replace it with: while IFS='=' read key value; do ... ; done < /the/file
3
while IFS='=' read -r k v; do
   : # do something with $k and $v
done < file

IFS is the 'inner field separator', which tells bash to split the line on an '=' sign.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.