Using variables in printf format

前端 未结 4 1335
挽巷
挽巷 2021-01-11 22:07

Suppose I have a file like this:

$ cat a
hello this is a sentence
and this is another one

And I want to print the first two columns with so

4条回答
  •  旧巷少年郎
    2021-01-11 22:26

    If you use * in your format string, it gets a number from the arguments

    awk '{printf "%*-s%s\n", 17, $1, $2}' file
    hello            this
    and              this
    

    awk '{printf "%*-s%s\n", 7, $1, $2}' file
    hello  this
    and    this
    

    As read in The GNU Awk User’s Guide #5.5.3 Modifiers for printf Formats:

    The C library printf’s dynamic width and prec capability (for example, "%*.*s") is supported. Instead of supplying explicit width and/or prec values in the format string, they are passed in the argument list. For example:

    w = 5
    p = 3
    s = "abcdefg"
    printf "%*.*s\n", w, p, s
    

    is exactly equivalent to:

    s = "abcdefg"
    printf "%5.3s\n", s
    

提交回复
热议问题