shell命令之基本的數組操作

Arrays in bash

1.將多行文本合併爲一行

i=0
while read line
do
arr[$i]=$line
((i++))
done
echo ${arr[@]}       //echo ${arr[@]}輸出所有的數組元素

**Input**
Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway
**Output**
Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway

2.將包含‘a’字母的文本行刪掉

i=0
while read line
do
arr[$i]=$line
((i++))
done
echo ${arr[@]/*[aA]*/}

**Input**
Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway
**Output**
Niger

**Output2**
echo ${arr[@]/*[aA]*/hello}  //使用hello替換掉所有包含a的文本行
hello hello hello hello hello hello Niger hello hello hello

3.將上述輸入文本重複輸出三次

X=$(paste -sd' ' fileName)
echo $X $X $X

X=$(cat fileName)
echo $X $X $X

**Output**
Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway

4.輸出某個元素

echo ${arr[3]}

5.統計輸入文本有多少行

a.使用wc命令
wc -l

b.使用echo命令
arr=($(cat))
echo ${#arr[@]}

c.使用for循環
i=0
while read line
do
arr[$i]=$line
((i++))
done
echo "$i"

6.將每行第一個大寫字母替換爲.

a.使用sed命令僅替換第一個大寫字母爲.
sed 's/[A-Z]/./' | paste -sd ' '

b.使用數組的替換來實現
X=($(cat)) 
echo "${X[@]/[A-Z]/.}"

**Output**
.amibia .auru .epal .etherlands .ewZealand .icaragua .iger .igeria .orthKorea .orway

7.找出一組數據中落單的數

a.首先將' '替換爲換行,然後對每行數據排序,獲取只出現一次的數字
tr ' ' '\n' | sort | uniq -u

題目出處:https://www.hackerrank.com/domains/shell/arrays-in-bash/page:1

發佈了342 篇原創文章 · 獲贊 78 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章