今天刷Leecode(192 Word frequency)時,遇到一個shell語法問題,記錄下來。首先將題目描述和代碼呈上
#!/bin/bash
# Write a bash script to calculate the frequency of each word in a text file words.txt.
#
# For simplicity sake, you may assume:
#? words.txt contains only lowercase characters and space' 'characters.
#? Each word must consist of lowercase characters only.
#? Words are separated by one or more whitespace characters.
#
# For example, assume that words.txt has the following content:
# the day is sunny the the
# the sunny is is
#
# Your script should output the following, sorted by descending frequency:
# the4
# is3
# sunny2
# day1
# define a map
declare -A map=()
# iterator lines in file
L24 #cat words.txt |whileread line
whileread line
do
forword in $line
do
? ? ? ? echo $word
if[ -z ${map[$word]} ];then
map[$word]=1
else
? ? ? ? ? ? let map[$word]++
? ? ? ? fi?
? ? done
L36done < words.txt
forkey in ${!map[@]}
do
? ? echo $key ${map[$key]}
done
題目的意思是統(tǒng)計一個文件中單詞重復的次數(shù),開始寫法如L24,while循環(huán)結(jié)束后,map依然為空,后來才知道是使用了管道的緣故
當啟用管道時,會生成一個subshell,while循環(huán)的代碼在subshell中執(zhí)行,那么變量map也是在subshell中被修改,
while循環(huán)結(jié)束后,回到主shell,map沒有被修改,也就是說,兩個map不是同一個map,while中修改的map是外層map的副本
修改代碼,將讀取文件的格式改成L36,程序運行正常