0

I’m trying to center-align a column using the command column.

The output should look like this:

temperatures  
    50  
    12  
    89  
    63  

How can I do this?

  • 1
    How about your input? Does it only have this column left-aligned? – rahul May 1 '15 at 22:36
  • yes. the input file is just 50 12 89 63 in a column. when i run the file i want it to be center aligned. – billy klarr May 1 '15 at 22:48
  • I didn’t notice that you wanted to use the column command until I wrote my answer. – yellowantphil May 1 '15 at 23:11
  • If you really need to use the column command, nothing comes to mind. It prints text left-aligned. – yellowantphil May 1 '15 at 23:21
  • What do you want your numbers centered in relation to?. Your sample output does not show them being centered in relation to temperatures. – Peter.O May 2 '15 at 8:57
0

I wrote this answer before noticing that you want to use the column command, but if that isn’t a requirement, you can center text with this bash shell script:

#!/bin/bash
set -e    # exit the script if something goes wrong

width=12
data="temperatures 50 12 89 63"

for word in $data; do
    strlen=$(printf $word | wc -c)
    w=$(( ($width - $strlen)/2 ))
    printf "%${w}s%s\n" "" $word
done

How it works:

  • $width is the column width
  • The for loop prints every word in $data
  • $strlen is the length of the current word, in bytes.
  • $w is the number of spaces to print before the word to make it centered.
  • printf prints $w spaces, followed by the word

Output:

temperatures
     50
     12
     89
     63

This script will only work for single-byte text encodings. You would need to change the strlen line to handle text containing a 🐱, for example.

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.