#!/bin/bash
# Read a string with spaces using for loop
for value in I like programming
echo $value
done
结果
$ sh test1.sh
programming
示例2:使用for循环迭代字符串变量
在变量StringVal中分配文本,并使用for循环读取此变量的值。最终效果跟上例相同
#!/bin/bash
# Define a string variable with a value
StringVal="Welcome to linuxhint"
# Iterate the string variable using for loop
for val in $StringVal; do
echo $val
done
结果
$ sh test2.sh
Welcome
linuxhint
示例3:迭代字符串值的数组
在此脚本中使用类型声明字符串值的数组。数组中包含空格的两个值是“ Linux Mint”和“ Red Hat Linux”。该脚本将这些值拆分为多个单词并将其打印为单独的值,从而生成输出。但这不是正确的输出。下一个示例显示了此类问题的解决方案。
#!/bin/bash
# Declare an array of string with type
declare -a StringArray=("Linux Mint" "Fedora" "Red Hat Linux" "Ubuntu" "Debian" )
# Iterate the string array using for loop
for val in ${StringArray[@]}; do
echo $val
done
结果
$ sh test3.sh
Linux
Fedora
Linux
Ubuntu
Debian
示例4:将多个单词的字符串值打印为单个值
#!/bin/bash
# Declare a string array with type
declare -a StringArray=("Windows XP" "Windows 10" "Windows ME" "Windows 8.1"
"Windows Server 2016" )
# Read the array values with space
for val in "${StringArray[@]}"; do
echo $val
done
结果:
$ sh test4.sh
Windows XP
Windows 10
Windows ME
Windows 8.1
Windows Server 2016
示例5:使用'*迭代数组的字符串值
#!/bin/bash
#Declare a string array
LanguageArray=("PHP" "Java" "C#" "C++" "VB.Net" "Python" "Perl")
# Print array values in lines
echo "Print every element in new line"
for val1 in ${LanguageArray[*]}; do
echo $val1
echo ""
# Print array values in one line
echo "Print all elements in a single line"
for val2 in "${LanguageArray[*]}"; do
echo $val2
echo ""
结果:
$ sh test5.sh
Print every element in new line
VB.Net
Python
Print all elements in a single line
PHP Java C# C++ VB.Net Python Perl
示例6:迭代以逗号分隔的字符串值
在这里,逗号(,)用于分割字符串值。 IFS变量用于设置字段分隔符。
#!/bin/bash
DataList=" HTML5, CCS3, BootStrap, JQuery "
Field_Separator=$IFS
# set comma as internal field separator for the string list
IFS=,
for val in $DataList;
echo $val
IFS=$Field_Separator
结果:
$ sh test6.sh
HTML5
BootStrap
JQuery
示例7:多个字符串数组一起读取
示例演示怎么合并多个数据并遍历出来
#! /bin/sh
str_array1=("Magento 2.2.4" "WooCommerce")
str_array2=("CodeIgnitor" "Laravel")
combine=(str_array1 str_array2)
for arrItem in ${combine[@]}
eval 'for val in "${'$arrItem'[@]}";do echo "$val";done'
done
结果:
$ sh test7.sh
Magento 2.2.4
WooCommerce
CodeIgnitor
Laravel
示例8:使用模式读取字符串列表
在这里,“ /,/”模式用于根据逗号分割字符串值。
#! /bin/sh
# Define a list of string variable
stringList=WordPress,Joomla,Magento
# Use comma as separator and apply as pattern
for val in ${stringList//,/ }
echo $val
done