4

I have an array that contains details about each NIC. Each array index consists of three space-separated values.

I would like to have a nice table as output. Is there a way to assign formatting patterns to each value in an index?

so far this is what I use:

NIC_details[0]='wlp2s0 192.168.1.221 xx:xx:xx:xx:xx:xx'
NIC_details[1]='wwan0 none xx:xx:xx:xx:xx:xx'
NIC_details[2]='virbr0 192.168.122.1 00:00:00:00:00:00'

printf "%-20s\n" "${NIC_details[@]}"

Is there a way to access the values in an array index by their position $1, $2, and $3, knowing that they are space-separated, and then apply a formatting pattern for each $X position?

I have also tried

echo "$i" | column -t

but it does not bring the desired result.

4

Here's a slight modification to what you were already doing:

set -f # to prevent filename expansion
for i in ${!NIC_index[@]}
do
  printf "%-20s" ${NIC_details[i]}
  printf "\n"
done

I added a for loop to go over all of the array indexes -- that's the ${!NIC... syntax. Since it's a numeric array, you could alternatively loop directly over the indexes.

Note that I intentionally left ${NIC_details[i]} unquoted so that the shell would split the value on the spaces that you've used to separate the values. printf thus sees the 3 values and so repeats the %-20s formatting for each of them. I then add a newline after each NIC to make a nice table.

The set -f at the top is important if we leave variables unquoted; otherwise the shell will step in and attempt to glob any wildcards it sees in unquoted variables.

Sample output:

wlp2s0              192.168.1.221       xx:xx:xx:xx:xx:xx
wwan0               none                xx:xx:xx:xx:xx:xx
virbr0              192.168.122.1       00:00:00:00:00:00
1

Yes there is a way, use awk.
One example :

echo ${NIC[0]} | awk '{ printf "%-10s %s\n", $1, $2 }'

Another way would be to get the values in different variables and then do the printf from bash. Like :

var1=$(echo ${NIC[0]} | cut -d ' ' -f1)
var2=$(echo ${NIC[0]} | cut -d ' ' -f2)
var3=$(echo ${NIC[0]} | cut -d ' ' -f3)

And use the printf with $var1,2,3 .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.