Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print list/array in columns

Tags:

shell

fish

I have list/array, for example the $PATH env variable, when you do echo $PATH it prints

/usr/local/bin /usr/bin /bin /usr/sbin /sbin /opt/X11/bin /usr/local/MacGPG2/bin /usr/texbin /usr/local/go/bin

I would like this to be formatted in columns like below, so don’t have to scroll up down much. The $PATH variable is just an example, I would like to way to be able to do it with any list.

/usr/local/bin /usr/sbin    /usr/local/MacGPG2/bin
/usr/bin       /sbin        /usr/texbin
/bin           /opt/X11/bin /usr/local/go/bin

I can print each item in the list in new row using a for loop but can’t figure out a way to do multiple columns. I know there is a column command but that doesn’t seem to do any thing. I’ve tried all the options like echo $PATH | column -c 5

like image 776
user14492 Avatar asked Sep 13 '26 12:09

user14492


1 Answers

Here you go: pass in a variable name and the number of columns you want

$ function columnize -a listvarname -a ncols
      test (count $ncols) -eq 1; or set ncols 1
      printf "%s\n" $$listvarname | \
      eval paste (yes - | head -n $ncols | tr '\n' " ") | \
      column -t
  end 

A demo using a non-special list name.

$ set list /usr/local/bin /usr/bin /bin /usr/sbin /sbin /opt/X11/bin /usr/local/MacGPG2/bin /usr/texbin /usr/local/go/bin

$ columnize list 3
/usr/local/bin          /usr/bin     /bin
/usr/sbin               /sbin        /opt/X11/bin
/usr/local/MacGPG2/bin  /usr/texbin  /usr/local/go/bin

$ columnize list 5
/usr/local/bin  /usr/bin                /bin         /usr/sbin          /sbin
/opt/X11/bin    /usr/local/MacGPG2/bin  /usr/texbin  /usr/local/go/bin

$ columnize list 
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
/opt/X11/bin
/usr/local/MacGPG2/bin
/usr/texbin
/usr/local/go/bin
like image 93
glenn jackman Avatar answered Sep 16 '26 06:09

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!