使用printf格式的变量

fed*_*qui 9 awk printf awk-formatting

假设我有一个这样的文件:

$ cat a
hello this is a sentence
and this is another one
Run Code Online (Sandbox Code Playgroud)

我想打印前两列,在它们之间有一些填充.由于这个填充可能会改变,我可以使用例如7:

$ awk '{printf "%7-s%s\n", $1, $2}' a
hello  this
and    this
Run Code Online (Sandbox Code Playgroud)

或者17:

$ awk '{printf "%17-s%s\n", $1, $2}' a
hello            this
and              this
Run Code Online (Sandbox Code Playgroud)

或者25,或......你明白了这一点:数字可能会有所不同.

然后弹出一个问题:是否可以为此分配变量N,而不是以%N-s格式对整数进行硬编码?

我尝试了这些事情没有成功:

$ awk '{n=7; printf "%{n}-s%s\n", $1, $2}' a
%{n}-shello
%{n}-sand

$ awk '{n=7; printf "%n-s%s\n", $1, $2}' a
%n-shello
%n-sand
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想知道是否可以这样做.如果不是,那么最好的解决方法是什么?

jay*_*ngh 18

如果*在格式字符串中使用 它,它将从参数中获取一个数字

awk '{printf "%*-s%s\n", 17, $1, $2}' file
hello            this
and              this
Run Code Online (Sandbox Code Playgroud)

awk '{printf "%*-s%s\n", 7, $1, $2}' file
hello  this
and    this
Run Code Online (Sandbox Code Playgroud)

正如GNU Awk用户指南中所述#5.5.3 printf格式的修饰符:

支持C库printf的动态宽度和预处理能力(例如,"%*.*s").它们不是在格式字符串中提供显式宽度和/或预定义值,而是在参数列表中传递.例如:

w = 5
p = 3
s = "abcdefg"
printf "%*.*s\n", w, p, s
Run Code Online (Sandbox Code Playgroud)

完全等同于:

s = "abcdefg"
printf "%5.3s\n", s
Run Code Online (Sandbox Code Playgroud)

  • 美丽:) +1 (4认同)
  • 不知道这个.+1老兄 (2认同)
  • 我所能做的只是坐下来点击+1 ...... :-).你知道我希望不存在哪些功能 - 能够在填充时指定任何主角字符.就像你可以做'awk'BEGIN {printf"%05d \n",17}''左边用零填充一样,如果你能做'awk'那么通常会很方便BEGIN {printf"%#5d \n",17}"用"#"或任何其他字符填充.这样,如果你想要一个5`#`的字符串你可以简单地做`awk'BEGIN {printf"%#5d \n",""}'`而不是'awk'BEGIN {print gensub(/ 0 /, "#","g",sprintf("%05d",""))}'或类似.哦,那里我们再次走向语言臃肿.. (2认同)

Ken*_*ent 5

这算吗?

想法正在构建“动态” fmt,用于printf.

kent$   awk '{n=7;fmt="%"n"-s%s\n"; printf fmt, $1, $2}' f 
hello  this
and    this
Run Code Online (Sandbox Code Playgroud)