1

bash 脚本中如何拼接字符串

 1 year ago
source link: https://www.51cto.com/article/740634.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
44222b945908c6faeed561d7af72be0409c25a.jpg

在几乎所有编程语言中,字符串连接都是一个很重要的组成部分。

在 bash 中也可以连接字符串,但是 bash 中没有用于字符串拼接的运算符,只需要将字符串一个一个的编写在一起即可。如下所示:

concat_string="$str1$str2"

下面我们以实际例子介绍一下如何在 bash 中拼接字符串。

字符串变量拼接

bash 中没有像其他大多数编程语言中那样的数据类型,但我们仍然可以在 bash 中声明变量。比如我们要声明一个字符串变量:

$'Welcome'

可以使用 printf 命令打印此字符串变量的值:​

$printf "$w\n"Welcome

我们先定义几个字符串变量:​

$'To
'$'Linux'
$'Handbook!'

那怎样将这些字符串拼接起来形成一个新的变量呢?

$"${w} ${t} ${l} ${h}"

通过这种方式,我将所有四个字符串连接到一个变量中,并将其命名为 tony。请注意,我在变量之间添加了一个空格。

然后我们验证一下新的字符串:​

$printf "$tony\n"Welcome To Linux Handbook!

下面是完整的 bash 脚本:​

#!/bin/bash
w='Welcome'
t='To'
l='Linux'
h='Handbook'
tony="${w} ${t} ${l} ${h}"
printf "${tony}\n"

设置其可执行权限,然后执行:​

$ chmod +x concat.sh
$ ./concat.sh
Welcome To Linux Handbook!

在进行字符串拼接时,包裹变量名的花括号 {} 不是必需的。不过为了让代码更易读,最好加上花括号 {}。

字符串追加

上面的例子是将多个字符串拼接为一个。那怎样将一串字符追加到某个已存在的字符串中呢?可以使用 += 运算符来实现。如下所示:​

str="iron"
str+="man"

这样,最后 str 的值是什么呢?答案是 ironman。​

$"iron"
$"man"
$echo $str
ironman

当我们在 bash 中使用循环的时候,这会很有用,如下例子:​

#!/bin/bash
var=""
for color in 'Black' 'White' 'Brown' 'Yellow'; do
"${color}
done
echo "$var"

运行上述脚本,其结果如下:

Black

连接数字和字符串

正如我们前文提到的,Bash 中没有数据类型。字符串和整数是相同的,因此它们可以很容易地连接到一个字符串中。

我们用上文中第二个脚本来看另一个示例。这次,我们用一个数字:​

#!/bin/bash
we='We'
lv='Love'
y='You'
morgan=3000
stark="${we} ${lv} ${y} ${morgan}!!!"
printf "${stark}\n"
$ chmod +x ​morgan.sh​​
$ ./morgan.sh
We Love You 3000!!!

字符串的嵌套拼接

上面例子中我们得到了两个连接后的字符串,也可以将这两个字符串嵌套拼接,存储在第三个字符串中。如下面脚本所示:​

#!/bin/bash
w='Welcome'
t='To'
l='Linux'
h='Handbook'
tony="${w} ${t} ${l} ${h}"
we='We'
lv='Love'
y='You'
morgan=3000
stark="${we} ${lv} ${y} ${morgan}!!!"
ironman="${tony}..${stark}"
printf "${ironman} Forever!\n"

下面是执行结果:

Welcome To Linux Handbook..We Love You 3000!!! Forever!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK