Home > Mobile >  Parsing an array with emty element
Parsing an array with emty element

Time:01-31

Hello I am trying to parse a file into an array which contains empty elements

Sample file (test)

test11|test12|test13|test14
test21||test23|test24

the following funtion just print the array elements

test_func()
{
    local param=($@)
    echo "1: ${param[1]}, 2: ${param[2]}, 3: ${param[3]}, 4: ${param[4]}"
}

And now I call this function as follows

while IFS=\| read f1 f2 f3 f4
do
    arr=("$f1" "$f2" "$f3" "$f4")
    test_func ${arr[@]}
done < test

I am using zsh 5.8.1 (x86_64-ubuntu-linux-gnu). I got the following output

1: test11, 2: test12, 3: test13, 4: test14
1: test21, 2: test23, 3: test24, 4: 

Note that in the second line the elements are shifted to the left.

I am not sure what I am doing wrong here. Can someone please help me on this?

Thanks

CodePudding user response:

You need to quote both ${arr[@]} and $@ in order to preserve the empty sting produced by each.

Unquoted parameter expansions are not subject to word-splitting, but the separate elements produced by an array expansion are not due to word-splitting. They are individual words in their own right, so failing to quote either the expansions mentioned above produces unquoted words. An unquoted empty string simply "goes away". If you leave $arr[@] unquoted, the empty string never makes it into test_func, and if leave $@ unquoted, the empty string is not present in the assignment to param.

test_func()
{
    local param=("$@")
    echo "1: ${param[1]}, 2: ${param[2]}, 3: ${param[3]}, 4: ${param[4]}"
}

while IFS=\| read f1 f2 f3 f4
do
    arr=("$f1" "$f2" "$f3" "$f4")
    test_func "${arr[@]}"
done < test

CodePudding user response:

It's much easier with awk command:

awk -F'\\|' -v OFS=', ' '{ for(i=1;i<=NF;i  ) $i=i": "$i }1' test.txt

1: test11, 2: test12, 3: test13, 4: test14
1: test21, 2: , 3: test23, 4: test24
  • Related