Bash provides string operations. We can use different operations like remove, find or concatenate strings in bash. In this tutorial we will look how to add or concatenate strings in Linux bash.
Bash提供字符串操作。 我们可以使用不同的操作,例如在bash中删除,查找或连接字符串。 在本教程中,我们将研究如何在Linux bash中添加或连接字符串。
并排放置变量 (Put Variables Side By Side)
The simplest and easy to understand way to concatenate string is writing the variables side by side. We will write the variables like $a$b . We do not need extra operater or function to use. In this example we will concatenate two variables named $a
and $b
into $c
.
连接字符串的最简单易懂的方法是并排编写变量。 我们将像$ a $ b这样写变量。 我们不需要额外的操作员或功能。 在此示例中,我们将两个名为$a
和$b
变量连接到$c
。
a="This is"
b="poftut.com website"
c=$a$b
echo $c
![Put Variables Side By Side](https://i-blog.csdnimg.cn/blog_migrate/aa77e34eb46a794166d5a361e57fad99.png)
双引号(Double Quotes)
Other useful alternative is using string variables inside strings which is defined with double quotes. We will put the variables name into double quotes with soe string. In this example we will put variable name $a
into string Welcome
其他有用的替代方法是在字符串中使用双引号定义的字符串变量。 我们将变量名称用soe字符串放在双引号中。 在本例中,我们将变量名$a
放入字符串Welcome
a=" to poftut"
c="Welcome $a"
echo $c
![Double Quotes](https://i-blog.csdnimg.cn/blog_migrate/246328342e266596c16072f9e794679f.png)
追加运算符(Append Operator)
Popular programming languages provides +=
compact add operator which is consist of plus and equal sign. We can add existing variable new string. This will add new string to the end of string variable. In this example variable named $a
has all ready string value Welcome
and we will add to poftut
like below.
流行的编程语言提供+=
紧凑的加法运算符,它由加号和等号组成。 我们可以添加现有变量新字符串。 这会将新字符串添加到字符串变量的末尾。 在此示例中,名为$a
变量具有所有就绪的字符串值Welcome
,我们将如下所示添加to poftut
中。
a="Welcome"
a+=" to poftut"
echo $a
![Append Operator](https://i-blog.csdnimg.cn/blog_migrate/acb5626881680a9aba0a9815d2bcf571.png)
Printf功能(Printf Function)
printf
is a function used to print and concatenate strings in bash. We can provide the string we want to print into a variable. We will use -v
option with the variable name and the string we want to add. In this example we will use string variable $a
and to poftut
.
printf
是用于在bash中打印和连接字符串的函数。 我们可以提供要打印到变量中的字符串。 我们将-v
选项与变量名和我们要添加的字符串一起使用。 在此示例中,我们将使用字符串变量$a
和to poftut
。
a="Welcome"
printf -v c "$a to poftut"
echo $c
![Printf Function](https://i-blog.csdnimg.cn/blog_migrate/510c30c7386ec191061c2e60d6aebae3.png)
翻译自: https://www.poftut.com/bash-concatenate-or-add-strings/