国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Linux Shell > 正文

shell數組常用實例分享

2020-07-27 19:23:55
字體:
來源:轉載
供稿:網友

說明:shell中數組的下標默認是從0開始的

1、將字符串放在數組中,獲取其長度

復制代碼 代碼如下:

#!/bin/bash
str="a b --n d"
array=($str)
length=${#array[@]}
echo $length

for ((i=0; i<$length; i++))
do
echo ${array[$i]}
done

執行結果:
[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

執行結果:
a

c

2、字符串用其他字符分割時

復制代碼 代碼如下:

#!/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]}

執行結果:
a

c

3、數組的其他操作

復制代碼 代碼如下:

#!/bin/bash
str="a b --n dd"
array=($str)
length=${#array[@]}

#ouput the first array element直接輸出的是數組的第一個元素
echo $array

#Use subscript way access array用下標的方式訪問數組元素
echo ${array[1]}

#Output the array輸出這個數組
echo ${array[@]}

#Output in the array subscript for 3 the length of the element輸出數組中下標為3的元素的長度
echo ${#array[3]}

#Output in the array subscript 1 to 3 element輸出數組中下標為1到3的元素
echo ${array[@]:1:3}

#Output in the array subscript greater than 2 elements輸出數組中下標大于2的元素
echo ${array[@]:2}

#Output in the array subscript less than 2 elements輸出數組中下標小于2的元素
echo ${array[@]::2}


執行結果:
a

a b --n dd
2
b --n dd
--n dd
a b

4、遍歷訪問一個字符串(默認是以空格分開的,當字符串是以其他分隔符分開時可以參考2)

復制代碼 代碼如下:

#!/bin/bash
str="a --m"
for i in $str
do
echo $i
done

執行結果:
a
--m

5、如何使用echo輸出一個字符串str="-n". 由于-n是echo的一個參數,所以一般的方法echo "$str"是無法輸出的.

解決方法可以有:

復制代碼 代碼如下:

echo x$str | sed 's/^x//'
echo -ne "$str/n"
echo -e "$str/n/c"
printf "%s/n" $str(這樣也可以)

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 许昌县| 抚远县| 临清市| 定州市| 铅山县| 彝良县| 乌什县| 张家口市| 峨眉山市| 广饶县| 从化市| 泾阳县| 台北县| 安泽县| 襄汾县| 皋兰县| 黄平县| 巴南区| 沙河市| 巴中市| 西华县| 汾西县| 句容市| 谢通门县| 拜城县| 突泉县| 洛宁县| 宾阳县| 汕尾市| 合水县| 新建县| 天镇县| 武鸣县| 六盘水市| 松潘县| 克东县| 简阳市| 久治县| 南昌市| 灯塔市| 黎城县|