shell數(shù)組常用實(shí)例分享
說明:shell中數(shù)組的下標(biāo)默認(rèn)是從0開始的
1、將字符串放在數(shù)組中,獲取其長(zhǎng)度
#!/bin/bash
str="a b --n d"
array=($str)
length=${#array[@]}
echo $length
for ((i=0; i<$length; i++))
do
echo ${array[$i]}
done
執(zhí)行結(jié)果:
[oracle@99bill-as9 array]$ sh length.sh
4
a
--n
d
2)、打印字符串:
#!/bin/bash
str="a b c"
for i in $str
do
echo $i
done
或者:
#!/bin/bash
str="a b c"
array=($str)
for ((i=0;i<${#array[@]};i++))
do
echo ${array[$i]}
done
執(zhí)行結(jié)果:
a
c
2、字符串用其他字符分割時(shí)
#!/bin/bash
str2="a#b#c"
a=($(echo $str2 | tr '#' ' ' | tr -s ' '))
length=${#a[@]}
for ((i=0; i<$length; i++))
do
echo ${a[$i]}
done
#echo ${a[2]}
執(zhí)行結(jié)果:
a
c
3、數(shù)組的其他操作
#!/bin/bash
str="a b --n dd"
array=($str)
length=${#array[@]}
#ouput the first array element直接輸出的是數(shù)組的第一個(gè)元素
echo $array
#Use subscript way access array用下標(biāo)的方式訪問數(shù)組元素
echo ${array[1]}
#Output the array輸出這個(gè)數(shù)組
echo ${array[@]}
#Output in the array subscript for 3 the length of the element輸出數(shù)組中下標(biāo)為3的元素的長(zhǎng)度
echo ${#array[3]}
#Output in the array subscript 1 to 3 element輸出數(shù)組中下標(biāo)為1到3的元素
echo ${array[@]:1:3}
#Output in the array subscript greater than 2 elements輸出數(shù)組中下標(biāo)大于2的元素
echo ${array[@]:2}
#Output in the array subscript less than 2 elements輸出數(shù)組中下標(biāo)小于2的元素
echo ${array[@]::2}
執(zhí)行結(jié)果:
a
a b --n dd
2
b --n dd
--n dd
a b
4、遍歷訪問一個(gè)字符串(默認(rèn)是以空格分開的,當(dāng)字符串是以其他分隔符分開時(shí)可以參考2)
#!/bin/bash
str="a --m"
for i in $str
do
echo $i
done
執(zhí)行結(jié)果:
a
--m
5、如何使用echo輸出一個(gè)字符串str="-n". 由于-n是echo的一個(gè)參數(shù),所以一般的方法echo "$str"是無法輸出的.
解決方法可以有:
echo x$str | sed 's/^x//'
echo -ne "$str\n"
echo -e "$str\n\c"
printf "%s\n" $str(這樣也可以)
相關(guān)文章
shell腳本聯(lián)合PHP腳本采集網(wǎng)站的pv和alexa排名
這篇文章主要介紹了shell腳本聯(lián)合PHP腳本采集網(wǎng)站的pv和alexa排名,本文使用PHP腳本采集alexa網(wǎng)站數(shù)據(jù),然后在shell中調(diào)用php腳本并輸出數(shù)據(jù),需要的朋友可以參考下2014-12-12
Linux下is not in the sudoers file的解決
當(dāng)我們使用sudo命令切換用戶的時(shí)候可能會(huì)遇到提示以下錯(cuò)誤:用戶名 is not in the sudoers file.本文給大家分享原因分析及解決方案,感興趣的朋友跟隨小編一起看看吧2023-02-02
linux設(shè)置定時(shí)任務(wù)的方法步驟
這篇文章主要介紹了linux設(shè)置定時(shí)任務(wù)的方法步驟,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-05-05

