📜  连接两个字符串的 Shell 脚本

📅  最后修改于: 2022-05-13 01:57:32.463000             🧑  作者: Mango

连接两个字符串的 Shell 脚本

字符串连接是将一个字符串附加到另一个字符串末尾的过程。这可以通过使用两种方法的 shell 脚本来完成:使用 +=运算符,或者简单地一个接一个地编写字符串。下面的示例显示了一些可用于连接字符串的shell 脚本。

示例 1:

在本例中,我们将使用+=运算符连接两个字符串。输入字符串将存储在两个变量ab 中

代码:

#Read inputs a and b and store string variables in them.
read a b

#append b to the string a
a+=$b

#Output the resulting string
echo $a



示例 2:

在这个例子中。我们将在 for 循环中使用 +=运算符连接多个变量,其中每两个字符串用空格分隔。

代码:

#create an empty string c
c=""

#read input strings and store them in a and b
read a b

#for loop to append a group of strings to the variable c.  
for val in $a 'ipsum' $b 'sit amet' 10
do
 c+="$val "
done

#The result is a string that consists of all the elements concatenated into a single string
echo "$c"

请注意,数组中的整数 10 被视为与字符串相同。这是因为在 shell 脚本中,变量是根据上下文处理的,而不是按类型隔离的。

示例 3:

在这个例子中,我们有两个变量 a 和 b,我们在每个变量中存储了一个字符串。我们想将它们一个接一个地连接起来。连接的结果将存储在变量 c 中。

代码:



#Read inputs a and b and store string variables in them.
read a b

#concatenate the strings by writing one after the other. Store the result in c
c=$a$b

#output c
echo $c

我们还可以通过简单地插入双引号“”包围的文本来添加额外的文本元素。在这种情况下,我们在两个字符串之间添加了一个空格,在它们之前添加了一个连字符,在它们之后添加了一个感叹号。另一种方法是用双引号 ” ” 将整个文本括起来,并用大括号 {} 将变量名括起来,这样字符串中的其他元素就不会干扰它们。

代码:

#Read inputs a and b and store string variables in them.
read a b

#concatenate the strings by putting one after the other. Store the result in c
c="-"$a" "$b"!"

#alternative solution:
#c="-${a} {b}!"

#output c
echo $c

示例 4:

这是另一个示例,它展示了如何通过一个接一个地写入字符串来连接字符串。在这种情况下,我们有 4 个字符串,其中两个存储在变量 a 和 b 中。

代码:

#Read inputs a and b and store string variables in them.
read a b

#concatenate the strings by putting one after the other
echo $a" ipsum "$b" sit amet"