使用printf格式变量 [英] Using variables in printf format

查看:225
本文介绍了使用printf格式变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  $猫
您好,这是一个句子
这是另一个

和我要在他们之间的一些填充打印头两列。由于这种填充可能会改变,我可以使用例如 7

  $的awk'{printf的%7-S%S \\ n,$ 1,$ 2}'一
您好,这
和这个

17

  $的awk'{printf的%17-S%S \\ n,$ 1,$ 2}'一
您好,这
和这个

25 ,或者......你看到这一点:数量可能会有所不同。

接着一个问题突然出现:是否有可能分配给该变量 N ,而不是硬编码在整数%氯化钠格式?

我想这些事情没有成功:

  $的awk'{N = 7; printf的%{N} -s%S \\ n,$ 1,$ 2}'一
%{N} -shello
%{N} -sand$ AWK'{N = 7; printf的%N-S%S \\ n,$ 1,$ 2}'一
%正shello
%N-沙

理想我想知道是否有可能做到这一点。如果不是,什么是最好的解决办法?


解决方案

如果您使用 * 在格式字符串,它得到了一些从参数

 的awk'{printf的%*  -  s%S \\ n,17,$ 1,$ 2}'文​​件
您好,这
和这个

 的awk'{printf的%*  -  s%S \\ n,7,$ 1,$ 2}'文​​件
您好,这
和这个


的GNUAwk用户指南#5.5.3修改程序的printf格式


  

C库的printf的动态宽度和preC的能力(例如,
  %*。*的)被支持。而不是提供明确的宽度和/或preC
  在格式字符串值,它们在参数列表中传递。对于
  例如:


  W = 5
P = 3
S =ABCDEFG
printf的%*。* S \\ n,W,P,S


  

是完全等价于:


  s =ABCDEFG
printf的%5.3s \\ n,S

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 some padding in between them. As this padding may change, I can for example use 7:

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

Or 17:

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

Or 25, or... you see the point: the number may vary.

Then a question popped: is it possible to assign a variable to this N, instead of hardcoding the integer in the %N-s format?

I tried these things without success:

$ 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

Ideally I would like to know if it is possible to do this. If it is not, what would be the best workaround?

解决方案

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

这篇关于使用printf格式变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆