转自: https://blog.csdn.net/shawhe/article/details/65631543
今天刷Leecode(192 Word frequency)时,遇到一个shell语法问题,记录下来。首先将题目描述和代码呈上
1 #!/bin/bash 2 3 # Write a bash script to calculate the frequency of each word in a text file words.txt. 4 # 5 # For simplicity sake, you may assume: 6 # words.txt contains only lowercase characters and space ' ' characters. 7 # Each word must consist of lowercase characters only. 8 # Words are separated by one or more whitespace characters. 9 # 10 # For example, assume that words.txt has the following content: 11 # the day is sunny the the 12 # the sunny is is 13 # 14 # Your script should output the following, sorted by descending frequency: 15 # the 4 16 # is 3 17 # sunny 2 18 # day 1 19 20 # define a map 21 declare -A map=() 22 23 # iterator lines in file 24 #cat words.txt | while read line 25 while read line 26 do 27 for word in $line 28 do 29 echo $word 30 if [ -z ${map[$word]} ];then 31 map[$word]=1 32 else 33 let map[$word]++ 34 fi 35 done 36 done < words.txt 37 38 for key in ${!map[@]} 39 do 40 echo $key ${map[$key]} 41 done
题目的意思是统计一个文件中单词重复的次数,开始写法如L24,while循环结束后,map依然为空,后来才知道是使用了管道的缘故
当启用管道时,会生成一个subshell,while循环的代码在subshell中执行,那么变量map也是在subshell中被修改,
while循环结束后,回到主shell,map没有被修改,也就是说,两个map不是同一个map,while中修改的map是外层map的副本
修改代码,将读取文件的格式改成L36,程序运行正常