用换行符在bash中构建字符串 [英] Build a string in bash with newlines

查看:114
本文介绍了用换行符在bash中构建字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历bash中的脚本,具体取决于要附加到变量的条件,然后在最后显示它,如下所示:

I'm going through a script in bash where depending on the conditionals I want to append to a variable different things and then display it at the very end, something like this:

VAR="The "

if [[ whatever ]]; then
    VAR="$VAR cat wears a mask"
elif [[ whatevs ]]; then
    VAR="$VAR rat has a flask"
fi

但是,如果我偶尔想在其中添加换行符,则尝试通过附加这种形式来建立VAR的方式而遇到麻烦.例如,我该怎么做VAR="$VAR\nin a box"?我以前曾见过$'\n'的用法,但由于附加而在尝试使用$VAR时也未见.

but i run into difficulties if I try to use this form of building up VAR by appending to it when I want to occasionally append newlines into it. How would I do VAR="$VAR\nin a box", for example? I have seen usage of $'\n' before but not when also trying to use $VAR because of the appending.

推荐答案

使用

您可以将$'\n'放在变量中:

newline=$'\n'
var="$var${newline}in a box"

在这种情况下,最好使用串联运算符:

By the way, in this case, it's better to use the concatenation operator:

var+="${newline}in a box"

如果您不喜欢ANSI-C引号,则可以将printf与它的-v选项一起使用:

If you don't like ANSI-C quoting, you can use printf with its -v option:

printf -v var '%s\n%s' "$var" "in a box"

然后,要打印变量var的内容,请不要忘记引号!

Then, to print the content of the variable var, don't forget quotes!

echo "$var"

或者更好,

printf '%s\n' "$var"

备注.请勿在Bash中使用大写的变量名.太糟糕了,有一天它将与一个已经存在的变量发生冲突!

Remark. Don't use upper case variable names in Bash. It's terrible, and one day it will clash with an already existing variable!

您还可以使用间接扩展功能(在

You could also make a function to append a newline and a string to a variable using indirect expansion (have a look in the Shell Parameter Expansion section of the manual) as so:

append_with_newline() { printf -v "$1" '%s\n%s' "${!1}" "$2"; }

然后:

$ var="The "
$ var+="cat wears a mask"
$ append_with_newline var "in a box"
$ printf '%s\n' "$var"
The cat wears a mask
in a box
$ # there's no cheating, look at the content of var:
$ declare -p var
declare -- var="The cat wears a mask
in a box"


只是为了好玩,这是append_with_newline函数的通用版本,它接受 n + 1 个参数( n≥ 1 ),并将它们全部连接在一起(第一个例外是使用换行符作为分隔符的将被扩展的变量的名称),并将答案放在变量中,变量的名称在第一个参数中给出:


Just for fun, here's a generalized version of the append_with_newline function that takes n+1 arguments (n≥1) and that will concatenate them all (with exception of the first one being the name of a variable that will be expanded) using a newline as separator, and puts the answer in the variable, the name of which is given in the first argument:

concatenate_with_newlines() { local IFS=$'\n'; printf -v "$1" '%s\n%s' "${!1}" "${*:2}"; }

看看效果如何:

$ var="hello"
$ concatenate_with_newlines var "a gorilla" "a banana" "and foobar"
$ printf '%s\n' "$var"
hello
a gorilla
a banana
and foobar
$ # :)

使用IFS"$*"这是一个有趣的骗术.

It's a funny trickery with IFS and "$*".

这篇关于用换行符在bash中构建字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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