📜  Bash 脚本 - 拆分字符串

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

Bash 脚本 - 拆分字符串

在本文中,我们将讨论如何在 bash 脚本中拆分字符串。

将单个字符串分成多个字符串称为字符串拆分。许多编程语言都有一个内置函数来执行字符串拆分,但 bash 中没有内置函数来执行此操作。有多种方法可以在 bash 中执行拆分字符串。让我们通过示例一一查看所有方法。

方法一:使用 IFS 变量

$IFS(Internal Field Separator) 是一个特殊的 shell 变量。它用于分配分隔符(一个或多个字符的序列,我们希望根据它来拆分字符串)。任何值或字符,如 '\t'、'\n'、'-' 等都可以作为分隔符。将值分配给 $IFS 变量后,需要读取字符串值。我们可以使用“-r”和“-a”选项读取字符串。

  • '-r':它将反斜杠(\)读作字符而不是转义字符
  • '-a':用于将拆分后的单词存储到一个数组变量中,该变量在 -a 选项之后声明。

示例 1:按空格分割字符串

代码:

#!/bin/bash

# String
text="Welcome to GeeksforGeeks"

# Set space as the delimiter
IFS=' '

# Read the split words into an array
# based on space delimiter
read -ra newarr <<< "$text"


# Print each value of the array by using
# the loop
for val in "${newarr[@]}";
do
 echo "$val"
done

输出:

Welcome
to
GeeksforGeeks

示例 2:按符号拆分字符串

使用@符号分割字符串。

代码:

#!/bin/bash

#String
text="Welcome@to@GeeksforGeeks@!!"

# Set @ as the delimiter
IFS='@'

# Read the split words into an array 
# based on space delimiter
read -ra newarr <<< "$text"


# Print each value of the array by 
# using the loop
for val in "${newarr[@]}";
do
 echo "$val"
done

输出:

Welcome
to
GeeksforGeeks
!!

方法 2:不使用 IFS 变量

在这种方法中,带有 -d 选项的 readarray 命令用于拆分字符串数据。 '-d':这个选项作为一个 IFS 变量来定义分隔符。

示例 1:按空格分割字符串

代码:

#!/bin/bash

# Read the main string
text="Welcome to GeeksforGeeks"

# Split the string by space
readarray -d " " -t strarr <<< "$text"

# Print each value of the array by 
# using loop
for (( n=0; n < ${#strarr[*]}; n++))
do
 echo "${strarr[n]}"
done

输出:

Welcome
to
GeeksforGeeks

示例 2:使用冒号作为分隔符进行拆分

代码:

#!/bin/bash

# Read the main string
text="Welcome:to:GeeksforGeeks"

# Split the string based on the delimiter, ':'
readarray -d : -t strarr <<< "$text"

# Print each value of the array by using
# loop
for (( n=0; n < ${#strarr[*]}; n++))
do
 echo "${strarr[n]}"
done

输出:

Welcome
to
GeeksforGeeks

方法 3:使用多字符分隔符拆分字符串

在此方法中,一个变量用于存储字符串数据,另一个变量用于存储多字符分隔符数据。还声明了一个数组变量来存储拆分后的字符串。

代码:

# Define the string to split
text="HelloRomy HelloPushkar HelloNikhil HelloRinkle"

# store multi-character delimiter 
delimiter="Hello"

# Concatenate the delimiter with the 
# main string
string=$text$delimiter

# Split the text based on the delimiter
newarray=()
while [[ $string ]]; do
 newarray+=( "${string%%"$delimiter"*}" )
 string=${string#*"$delimiter"}
done

# Print the words after the split
for value in ${newarray[@]}
do
 echo "$value "
done

输出:

Romy  
Pushkar  
Nikhil  
Rinkle