bash printf:忽略参数或按索引访问? [英] bash printf: ignore parameters or access by index?

查看:39
本文介绍了bash printf:忽略参数或按索引访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 bash 函数,它可以获取值(使用 curl 和 cut)并从中创建一个文件名.现在我想支持需要一组不同参数的第二个命名方案.

I have a bash function that fetches values (using curl and cut) and creates a file name from them. Now I want to support a second naming scheme that needs a different set of parameters.

示例:

#!/bin/bash

TEMPLATE="%02i. %s.txt"

foo() {
    a="Imagine these to"
    b="be set dynamically"
    c="42"

    filename="$(printf "$TEMPLATE" "$c" "$a")"
    # second: filename="$a - $b.txt"
    # or:     filename="$(printf "%s - %s.txt" "$a" "$b")"
    echo "$filename"
    # generate file
}

# actual script loops over:
foo

其中一个值是一个数字,如果需要,应该用前导零填充,因此在当前实现中是 printf.

One of the values is a number that should be padded with leading zeros if required, thus printf in the current implementation.

有没有办法通过全局设置不同的模板来实现这一点?这将要求模板可以通过索引访问参数或至少跳过其中的一些.

Is there a way to implement this with just setting a different template globally? This would require that the template can access parameters by index or at least skip some of them.

如果没有,我的选择是什么?模板由命令行参数选择,初始化后不改变.

If not, what are my alternatives? The template is to be chosen by command line parameter and does not change after initialization.

什么不起作用:

  • bash 手册页建议零长度输出是不可能的(跳过值)
  • C 的 printf 手册页提到了%m$"结构,但 bash 显然不支持该结构
  • 函数本身会生成值,因此它无法接收完整的文件名作为参数

推荐答案

如果需要跳过一个参数,可以使用 %.s.示例:

If you need to skip an argument, you can use %.s. Examples:

$ printf "%.s%s\n" "Bonjour" "Hello"
Hello
$ printf "%s%.s\n" "Bonjour" "Hello"
Bonjour

AFAIK,你不能通过索引访问参数.

AFAIK, you can't access arguments by index.

如果您需要将格式化的字符串存储在变量中,请不要使用子shell,如:

If you need to store the formated string in a variable, please don't use a subshell as in:

$ variable=$(printf "%.s%s" "Bonjour" "Hello")
$ echo "$variable"
Hello

相反,将 -v 选项用于 printf(键入 help printf 以获取详细信息),如下所示:

Instead, use the -v option to printf (type help printf to have the details) as in:

$ printf -v variable "%.s%s" "Bonjour" "Hello"
$ echo "$variable"
Hello

此外,如果您的模板可以来自用户输入,我建议您在它之前添加 --(这是为了结束命令的选项,以防万一用户想要用破折号开始一个模板).因此我会替换你的行

Also, if your template can come from user input, I would advise you to add -- just before it (this is to end the options of the command, just in case a user wants to start a template with a dash). Hence I would replace you line

filename="$(printf "$TEMPLATE" "$c" "$a")"

printf -v filename -- "$TEMPLATE" "$c" "$a"

最后,使用大写变量名被认为是不好的 bash 做法.

Finally, having upper case variable names is considered bad bash practice.

这篇关于bash printf:忽略参数或按索引访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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