【发布时间】:2019-01-30 00:54:13
【问题描述】:
我正在编写一个脚本,它将遍历列以查找单词的实例。
我决定通过嵌套循环执行此操作,但在执行我的代码后,我收到此错误:
./gallupscript.sh:第 115 行:意外标记附近的语法错误
done' ./gallupscript.sh: line 115:done'
这是我的代码失败的区域:
token=2 #token is the column number
starter=0
s1="First" ; s2="Second" ; s3="Third" ; s4="Fourth" ; s5="Fifth"
s=s ; a=1
while [ $token -le 6 ]
do
cat gallup.csv | cut -d',' -f"$token" | grep -n $strength1 | cut -d':' -f1 > str1
if [ -s str1 ]
then
for i in $(cat str1)
do
if [[ $i -ne $number && $starter -eq 0 ]]
then
save=$(cat gallup.csv | head -$i | tail +$i | cut -d',' -f1)
s=s ; s+=$a ; starter=1
printf "-- $strength1 --"
printf "${!s} Strength: $save"
elif [[ $i -ne $number && $starter -ne 0 ]]
then
save=$(cat gallup.csv | head -$i | tail +$i | cut -d',' -f1)
printf ", $save"
fi
done
starter=0
a=$((a+1))
token=$((token+1))
echo #new line
done
此代码应输出与我正在搜索的单词匹配的名称(在第一列中)。
【问题讨论】:
-
shellcheck.net 会告诉你错误的确切位置:你的
if [ -s str1 ]没有fi。 -
顺便说一句,见DontReadLinesWithFor;使用
printf时,为变量使用带占位符的格式字符串(printf '-- %s --' "$strength1"或printf ', %s' "$save"),以防止这些变量的内容被格式说明符误解;并修复 shellcheck.net 识别的各种其他引用问题。 -
哇,非常感谢!我不敢相信我错过了哈哈
-
...根本不知道为什么要使用
str1文件,而不仅仅是将管道捕获到变量中。甚至可以直接将其捕获到数组中:readarray -t items < <(cut -d',' -f"$token" <gallup.csv | grep -n "$strength1" | cut -d':' -f1); for item in "${items[@]}"; do ... -
感谢您的提示,我一定会使用它。
标签: bash