Bash教程

Bash 连接字符串

Bash 连接字符串

在本主题中,我们已经解释了如何在 Bash Shell 脚本中添加或连接字符串。
在 bash 脚本中,我们可以添加或将两个或多个字符串连接在一起,这称为字符串连接。这是任何编程语言的共同要求之一。应用特殊字符或内置函数来执行字符串连接。但是,Bash 不包含任何用于组合字符串数据或变量的内置函数。在 bash 中执行字符串连接最简单的方法是并排写入变量。
例如,假设我们有两个字符串(即"welcome"和"to lidihuo "),然后我们将两个字符串连接在一起并创建一个新字符串("welcome to lidihuo")。这个概念被称为字符串连接。

Command

连接字符串的示例命令可以定义为:
str3="$str1$str2"
注意: 注意上面的命令;赋值(=) 运算符之前或之后不应有任何空格。 'str' 用于表示字符串。
此命令将连接 str1 和 str2 的值并将其存储在第三个变量 str3 中。
以下是一些演示字符串连接不同方式的示例:

示例 1: 并排写入变量

这是字符串连接的基本示例,我们在此方法中不需要任何额外的运算符或函数。
Bash 脚本
#!/bin/bash
#Script to Concatenate Strings
#Declaring the first String 
str1="We welcome you"
#Declaring the Second String
str2=" on lidihuo."
#Combining first and second string
str3="$str1$str2"
#Printing a new string by combining both 
echo $str3
输出
     We welcome you on lidihuo.

示例 2: 使用双引号

另一种简单的方法是在字符串中使用变量,该字符串用双引号定义。字符串变量可以应用于字符串数据的任何位置。
Bash Script
#!/bin/bash
#Script to Concatenate Strings
#Declaring String Variable
str="We welcome you"
#Add the variable within the string
echo "$str on lidihuo."
输出
     We welcome you on lidihuo.

示例 3: 在循环中使用追加运算符

大多数流行的编程语言都支持追加运算符(+=),它是加号和等号的组合。它将在字符串变量的末尾添加新的字符串。
Bash 脚本
#!/bin/bash
echo "Printing the name of the programming languages"
#Initializing the variable before combining
lang=""
#for loop for reading the list
for value in 'java''python''C''C++';
do
lang+="$value "  #Combining the list values using append operator
done
#Printing the combined values
echo "$lang"
输出
Bash Concatenate String

示例 4: 使用 Printf 函数

在 bash 中,printf 是一个用于打印和连接字符串的函数。
Bash 脚本
#!/bin/bash
str="Welcome"
printf-v new_str "$str to lidihuo."
echo $new_str
输出
     Welcome to lidihuo.

示例 5: 使用文字字符串

还可以使用花括号对文字字符串执行字符串连接{}。它们的使用方式应该使变量不会与文字字符串混淆。
Bash 脚本
#!/bin/bash
str="Welcome to"
newstr="${str} lidihuo."
echo "$newstr"
输出
     Welcome to lidihuo.

示例 6: 使用下划线

在 bash shell 中使用下划线连接字符串是常见任务之一。它主要用于为文件分配名称。
Bash 脚本
#!/bin/bash
str1="Hello"
str2="World!"
echo "${str1}_${str2}"
输出
     Hello_World!

示例 7: 使用任意字符

Bash 脚本
#!/bin/bash
#String Concatenation by Character (,) with User Input
read-p "Enter First Name: " name
read-p "Enter State: " state
read-p "Enter Age: " age
combine="$name,$state,$age"
echo "Name, State, Age: $combine"
输出
Bash Concatenate String

结论

字符串连接是编程语言中生成有意义的输出所需的功能之一。本主题解释了几乎所有在 bash 中连接字符串的可能方法。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4