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"
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"