Padding characters in printf

前端 未结 13 834
半阙折子戏
半阙折子戏 2020-11-30 16:58

I am writing a bash shell script to display if a process is running or not.

So far, I got this:

printf \"%-50s %s\\n\" $PROC_NAME [UP]
13条回答
  •  长情又很酷
    2020-11-30 17:48

    Simple Console Span/Fill/Pad/Padding with automatic scaling/resizing Method and Example.

    function create-console-spanner() {
        # 1: left-side-text, 2: right-side-text
        local spanner="";
        eval printf -v spanner \'"%0.1s"\' "-"{1..$[$(tput cols)- 2 - ${#1} - ${#2}]}
        printf "%s %s %s" "$1" "$spanner" "$2";
    }
    

    Example: create-console-spanner "loading graphics module" "[success]"

    Now here is a full-featured-color-character-terminal-suite that does everything in regards to printing a color and style formatted string with a spanner.

    # Author: Triston J. Taylor 
    # Date: Friday, October 19th, 2018
    # License: OPEN-SOURCE/ANY (NO-PRODUCT-LIABILITY OR WARRANTIES)
    # Title: paint.sh
    # Description: color character terminal driver/controller/suite
    
    declare -A PAINT=([none]=`tput sgr0` [bold]=`tput bold` [black]=`tput setaf 0` [red]=`tput setaf 1` [green]=`tput setaf 2` [yellow]=`tput setaf 3` [blue]=`tput setaf 4` [magenta]=`tput setaf 5` [cyan]=`tput setaf 6` [white]=`tput setaf 7`);
    
    declare -i PAINT_ACTIVE=1;
    
    function paint-replace() {
        local contents=$(cat)
        echo "${contents//$1/$2}"
    }
    
    source <(cat <

    To print a color, that's simple enough: paint-format "&red;This is %s\n" red And you might want to get bold later on: paint-format "&bold;%s!\n" WOW

    The -l option to the paint-format function measures the text so you can do console font metrics operations.

    The -v option to the paint-format function works the same as printf but cannot be supplied with -l

    Now for the spanning!

    paint-span "hello " . " &blue;world" [note: we didn't add newline terminal sequence, but the text fills the terminal, so the next line only appears to be a newline terminal sequence]

    and the output of that is:

    hello ............................. world

提交回复
热议问题