假设我有一个像这样的文件:
$ cat a
hello this is a sentence
and this is another one
我想打印前两列,中间有一些填充。由于此填充可能会更改,因此我可以使用7
:
$ awk '{printf "%7-s%s\n", $1, $2}' a
hello this
and this
或17
:
$ awk '{printf "%17-s%s\n", $1, $2}' a
hello this
and this
或25
或…您明白了这一点:数字可能有所不同。
然后出现一个问题:是否可以向this分配变量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
理想情况下,我想知道是否可以这样做。如果不是,最好的解决方法是什么?
如果*
在格式字符串中使用,它将从参数中获取一个数字
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
如《 GNU Awk用户指南#5.5.3 printf格式的修饰符》所述:
支持C库printf的动态宽度和精度功能(例如,“%*。* s”)。而不是在格式字符串中提供显式的宽度和/或prec值,而是在参数列表中传递它们。例如:
w = 5
p = 3
s = "abcdefg"
printf "%*.*s\n", w, p, s
完全等同于:
s = "abcdefg"
printf "%5.3s\n", s
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句