0

I want to print the values from properties file dynamically I am using below code but getting wrong output.

testProperty.properties

edmcws,edmbws,edmwt

Code

file=/ThreadDump/testProperty.properties

count=$(head -1 $file | sed 's/[^,]//g' | wc -c)
echo "$count"

for((i=1;i<=$count;i++))
do
abc=$(awk -F "," '(NR==1){print $($i)}' $file)

echo "$abc"
done

Output

3
edmcws,edmbws,edmwt
edmcws,edmbws,edmwt
edmcws,edmbws,edmwt

But when I hard-code the value I am getting correct output.

Code

file=/ThreadDump/testProperty.properties

count=$(head -1 $file | sed 's/[^,]//g' | wc -c)
echo "$count"

for((i=1;i<=$count;i++))
do
abc=$(awk -F "," '(NR==1){print $1}' $file)

echo "$abc"
done

Output

3
edmcws
edmcws
edmcws

2 Answers 2

1

Since the awk body is in single quotes, awk does not see the shell variable. awk thinks you mean an awk variable i. That variable is undefined, so in a numeric context it has the value zero. Thus $i is interpreted by awk as $0, or the whole line.

You need to pass the shell variable into awk.

for ((i=1; i<=$count; i++))
do
    abc=$(awk -F "," -v col=$i 'NR==1 {print $col}' $file)
    #................^^^^^^^^^...............^^^^
    echo "$abc"
done

However, there's a better way than calling awk 3 separate times:

while IFS=, read -ra fields; do
    printf "%s\n" "${fields[@]}"
    # or do stuff with the individual fields
    for ((i=0; i < ${#fields[@]}; i++)); do
        echo "${fields[i]}"
    done
done < "$file" 
  • the while loop, with the file's contents redirected into it, loop over the lines of the file
  • IFS=, instructs the read command to do word splitting on commas
  • read -r means to not interpret any special characters as anything but regular chars.
  • read -a fields reads the words in the line into an array variable named fields
0
1

You are using abc=$(awk -F "," '(NR==1){print $($i)}' $file). Here you use single quotes around your awk skript. Therefore variables like $i are not replaced by their value.

If i=1, awk will therefore literally see $($i) instead of $1 as given in the second example.

You can give variables to awk using the -v option.

Maybe awk is not the perfect tool for the job. I would probably simply use

perl -wnle 'print for split ","'
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .