bash shell脚本中的SPRINTF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4377871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:55:24  来源:igfitidea点击:

SPRINTF in shell scripting?

bashshellprintf

提问by Manu R

I have an auto-generated file each day that gets called by a shell script. But, the problem I'm facing is that the auto-generated file has a form of:

我每天都有一个自动生成的文件,由 shell 脚本调用。但是,我面临的问题是自动生成的文件具有以下形式:

FILE_MM_DD.dat

... where MM and DD are 2-digit month and day-of-the-month strings.

... 其中 MM 和 DD 是两位数的月份和月份日期字符串。

I did some research and banged it at on my own, but I don't know how to create these custom strings using only shell scripting.

我进行了一些研究并自己进行了尝试,但我不知道如何仅使用 shell 脚本来创建这些自定义字符串。

To be clear, I am aware of the DATE function in Bash, but what I'm looking for is the equivalent of the SPRINTF function in C.

明确地说,我知道 Bash 中的 DATE 函数,但我正在寻找的是等效于 C 中的 SPRINTF 函数。

回答by Paused until further notice.

In Bash:

在 Bash 中:

var=$(printf 'FILE=_%s_%s.dat' "$val1" "$val2")

or, the equivalent, and closer to sprintf:

或者,等价的,更接近于sprintf

printf -v var 'FILE=_%s_%s.dat' "$val1" "$val2"

If your variables contain decimal values with leading zeros, you can remove the leading zeros:

如果您的变量包含带前导零的十进制值,您可以删除前导零:

val1=008; val2=02
var=$(printf 'FILE=_%d_%d.dat' $((10#$val1)) $((10#$val2)))

or

或者

printf -v var 'FILE=_%d_%d.dat' $((10#$val1)) $((10#$val2))

The $((10#$val1))coerces the value into base 10 so the %din the format specification doesn't think that "08" is an invalid octal value.

$((10#$val1))值强制为基数 10,因此%d格式规范中的“08”不认为是无效的八进制值。

If you're using date(at least for GNU date), you can omit the leading zeros like this:

如果您正在使用date(至少对于 GNU date),您可以像这样省略前导零:

date '+FILE_%-m_%-d.dat'

For completeness, if you want to addleading zeros, padded to a certain width:

为了完整起见,如果要添加前导零,请填充到特定宽度:

val1=8; val2=2
printf -v var 'FILE=_%04d_%06d.dat' "$val1" "$val2"

or with dynamic widths:

或使用动态宽度:

val1=8; val2=2
width1=4; width2=6
printf -v var 'FILE=_%0*d_%0*d.dat' "$width1" "$val1" "$width2" "$val2"

Adding leading zeros is useful for creating values that sort easily and align neatly in columns.

添加前导零对于创建易于排序并在列中整齐对齐的值非常有用。

回答by Daniel B?hmer

Why not using the printf program from coreutils?

为什么不使用 coreutils 的 printf 程序?

$ printf "FILE_%02d_%02d.dat" 1 2
FILE_01_02.dat

回答by kenorb

Try:

尝试:

sprintf() { local stdin; read -d '' -u 0 stdin; printf "$@" "$stdin"; }

Example:

例子:

$ echo bar | sprintf "foo %s"
foo bar