Using variables in printf format

前端 未结 4 1285
挽巷
挽巷 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:14

    Using simple string concatenation.

    Here "%", n and "-s%s\n" concatenates as a single string for the format. Based on the example below, the format string produced is %7-s%s\n.

    awk -v n=7 '{ printf "%" n "-s%s\n", $1, $2}' file
    awk '{ n = 7; printf "%" n "-s%s\n", $1, $2}' file
    

    Output:

    hello  this
    and    this
    

提交回复
热议问题