在sprintf的shell脚本? [英] SPRINTF in shell scripting?

查看:1052
本文介绍了在sprintf的shell脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自动生成的文件中的每一天,得到由一个shell脚本调用。
但是,我所面临的问题是,自动生成的文件具有的一种形式:

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:

FILE_MM_DD.dat

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

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

我做了一些研究,并猛敲它在我自己,但我不知道如何创建仅使用shell脚本这些自定义字符串。

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.

要明确,我知道在猛砸日期的功能,但我正在寻找的是在C sprintf函数的等价物。

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.

推荐答案

在击:

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

,或等效的,并接近的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)))

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

$((10#$ VAL1))强制转换的价值转化基地10所以%d个中格式规范并不认为08是一个无效的八进制值。

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

如果你使用日期(至少对于GNU 日期),你可以省略像前导零这样的:

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

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

有关完整性,如果你想的添加的前导零,填充到一定宽度:

For completeness, if you want to add leading 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.

这篇关于在sprintf的shell脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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