I have an options file of the following format

option1 = value1
option2 = value2
   ..... ; variable number of options
   .....
page_size= pagesize1 ;Note there is no space between page_size and =
page_size= pagesize2
page_size= pagesize3

During a regression test I want to extract the values for these options. Since the keywords "option1", option2, ... are different from each other, I can use awk to extract the values of value1, value2 as follows.

value1=$(awk '/option1/ {print $3}' $optfile)
value2=$(awk '/option2/ {print $3}' $optfile)

Now the problem is with the values for page_size. Although there can be multiple values for page_size, the following statement of awk

pagesize1=$(awk '/ page_size=/ {print $2}' $optfile)

gives me only the corresponding value for the first match of page_size.

So do any of you know of a way to get all three page sizes using awk?
Thanks.

I'd use arrays:

#!/bin/ksh
optfile=filename
set -A opts $(awk 'BEGIN {FS="="} { if($0~ / page_size/) { print $2}}' $optfile)
for i in 0 1 2
do
    echo ${opts[i]}
done

If you're using bash just "declare" opts as an array.

commented: Thanks. +3

I tried it in my cygwin bash shell. Maybe it is something unexpected in cygwin, but all the matches were stored in opts[0]. So ultimately I could do this without using arrays. :eek:

page_size=$(awk 'BEGIN {FS="="} { if($0~ /paper_size/) { print $2}}' $optfile)
for paper_size in $page_size; do
    echo $paper_size
done

But thanks a lot really. Your reply pointed me in the correct direction.

He did write:

If you're using bash just "declare" opts as an array.

That is:

declare -a opts

Notice the

#!/bin/ksh

at the start of his code.

Yes. I saw and did that.

By the way, I wouldn't bother with awk.

#!/bin/ksh
set -A opts $(sed -n 's/^ *paper_size *= *\(.*\)$/\1/p' optsfile)
for opt in ${opts
[*]} ; do
    echo $opt
done

Notice: I like to be able to use white space to keep it readable. The '*' matches zero or more occurances.

I'd use arrays:

#!/bin/ksh
optfile=filename
set -A opts  \
$(awk 'BEGIN {FS="="} { if($0~ / page_size/) { prinf("%s  ", $2}}' $optfile; echo"")
for i in 0 1 2
do
    echo ${opts[i]}
done

If you're using bash just "declare" opts as an array.

I changed it so awk puts it all on the same line.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.