Raymond gsh
Raymond gsh

Reputation: 383

Printing Tabular data using bash to fit the screen width

I am printing the name of the files processed with my bash script. since there were many file paths being processed. I decided to make them be printed similar to ls command which prints tabular with respect to the width of the screen. But I dunno how many columns I can have in my screen and that can be totally different on monitor is there any automatic way to do it? or a simple function which would compute width and compare it to size of the strings...

printf "%s\t" "$FILENAME"

Upvotes: 1

Views: 2081

Answers (2)

pjh
pjh

Reputation: 8164

In Bash you can get the screen width and height from the COLUMNS and LINES builtin variables.
As described in another answer, you can get the length of a string in Bash by using ${#var}.
You might find the ancient and venerable pr utility useful for generating output in columns.

Upvotes: 1

user4832408
user4832408

Reputation:

Generally this job is done using the tput program as follows:

#!/bin/sh

columns=$(tput cols)
lines=$(tput lines)

printf "terminal dimensions are: %sx%s\n" "$columns" "$lines"

To determine the number of characters in your strings do as follows:

#!/bin/sh

MYSTRING="This a long string containing 38 bytes"

printf "Length of string is %s\n" "${#MYSTRING}"

Taking advantage of the shell's ability to measure strings with ${#var}. Here is an example which puts these techniques together to format and center text:

#!/bin/sh

columns=$(tput cols)
lines=$(tput lines)
string="This text should be centered"
width="${#string}"
adjust=$(( (columns - width ) / 2))
longspace="                                             "

printf "%.*s" "$adjust" "$longspace"
printf "%s" "${string}"
printf "%.*s" "$adjust" "$longspace"
printf "\n"

Upvotes: 2

Related Questions