string 你如何附加到一个已经存在的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2250131/
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
How do you append to an already existing string?
提问by Mint
I want append to a string so that every time I loop over it will add say "test" to the string.
我想附加到一个字符串,以便每次循环时都会在字符串中添加“test”。
Like in PHP you would do:
就像在 PHP 中一样,你会这样做:
$teststr = "test1\n"
$teststr .= "test2\n"
echo = "$teststr"
echos:
回声:
test1
test2
But I need to do this in a shell script
但我需要在 shell 脚本中执行此操作
回答by William Pursell
In classic sh, you have to do something like:
在经典 sh 中,您必须执行以下操作:
s=test1
s="${s}test2"
(there are lots of variations on that theme, like s="$s""test2"
)
(该主题有很多变化,例如s="$s""test2"
)
In bash, you can use +=:
在 bash 中,您可以使用 +=:
s=test1
s+=test2
回答by ghostdog74
$ string="test"
$ string="${string}test2"
$ echo $string
testtest2
回答by Jim
#!/bin/bash
message="some text"
message="$message add some more"
echo $message
some text add some more
一些文字添加更多
回答by Ignacio Vazquez-Abrams
teststr=$'test1\n'
teststr+=$'test2\n'
echo "$teststr"
回答by Manuelsen
VAR=$VAR"$VARTOADD(STRING)"
echo $VAR
回答by Aditya
#!/bin/bash
msg1= #First Parameter
msg2= #Second Parameter
concatString=$msg1"$msg2" #Concatenated String
concatString2="$msg1$msg2"
echo $concatString
echo $concatString2