arraysshellawk

Printing array contents in the same line in awk


I have a script where I need to print the array contents in the same line of the previous print statement. Here array is dynamic in size and I have already one print statement which shows column wise output.

For example: let array having 3 contents (arr[1]=2,arr[2]=4,arr[3]=6), min=100, max=200. I have print statement which is printing column wise result.

gawk '{
  ...
  ...
print "Min:" min "\tMax:" max 
for (itr in arr)
print arr[i] " "

}' script.txt

Expected Output:

Min:100  Max:200  2 4 6 

My output:

Min:100 Max:200
2
4
6

Please suugest me an approach, how to append the array contents in previous print result.


Solution

  • Try using echo it has -n option to skip printing newline at the end.

    gawk '{
      ...
      ...
    echo -n "Min:" min "\tMax:" max 
    for (itr in arr)
    echo -n arr[i] " "
    
    }' script.sh
    

    Another Approach

    gawk '{
      ...
      ...
    printf "Min:" min "\tMax:" max 
    for (itr in arr)
    printf arr[i] " "
    
    }' script.sh
    

    Please refer echo documentation.