【问题标题】:How to use printf with variables, strings and new lines to write to a file in one line in bash如何使用带有变量、字符串和新行的 printf 在 bash 中的一行中写入文件
【发布时间】:2018-09-19 19:00:30
【问题描述】:

我想将变量、字符串和新行的 printf 打印到 bash 中的文件中,并且在一行中。我会使用 echo,但 echo 似乎有不同的解释,并且在其他问题上推荐了 printf。

NAME="karl"
printf %"s\n" this is $(NAME) hello! > my_file

当我执行cat my_file 时,我希望它如下所示:

this
is
karl
hello!

【问题讨论】:

    标签: bash


    【解决方案1】:

    我想你只是想要这个:

    name="karl"
    printf "%s\n" this is "$name" hello! > my_file
    

    您的代码的唯一问题是您使用的是$()(命令替换)而不是标准参数扩展。也就是说,您的格式说明符看起来很奇怪,因为它通常写成 %s(它仍然可以按照您的方式编写,因为 shell 会使用引号)。

    引号始终是防止分词(例如名称中的空格会出现在不同的行)和全局扩展(a* 之类的名称会扩展为以a 开头的路径列表)的好主意。

    【讨论】:

      【解决方案2】:

      尝试将printf 行替换为

      sed 's/[[:space:]]/\n/g ' <<< "this is ${NAME} hello!" > my_file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-01
        • 2014-04-18
        • 2021-04-08
        • 1970-01-01
        • 1970-01-01
        • 2017-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多