我正在構建一個腳本來計算給定字符串中兩個字母的出現次數。我無法弄清楚如何使變量成爲一個可測試的數字。Bash語法錯誤:算術運算期望的操作數
#!/bin/bash
touch ~/trfindlog.txt ~/trfindt ~/trfindr
echo $1 > ~/trfindlog.txt
cat ~/trfindlog.txt | grep -oi r | wc -l > ~/trfindr
cat ~/trfindlog.txt | grep -oi t | wc -l > ~/trfindt
varR='/trfindr'
varT='/trfindt'
if [[ "${varR}" -eq 0 && "${varT}" -eq 0 ]]
then
echo "This phrase contains no Rs or Ts."
elif [[ "${varR}" -eq 1 && "${varT}" -eq 1 ]]
then
echo "This phrase contains 1 R and 1 T."
elif [[ "${varR}" -gt 1 && "${varT}" -eq 1 ]]
then
echo "This phrase contains ${varR} Rs and 1 T."
elif [[ "${varR}" -eq 1 && "${varT}" -gt 1 ]]
then
echo "This phrase contains 1 R and ${varT} Ts."
elif [[ "${varR}" -gt 1 && "${varT}" -gt 1 ]]
then
echo "This phrase contains ${varR} Rs and ${varT} Ts."
fi
rm ~/trfindlog.txt ~/trfindt ~/trfindr
exit
此腳本給了我以下錯誤。
/automount/home/jcampbell/tools/itc/trfind.sh: line 12: [[: /trfindr: syntax error: operand expected (error token is "/trfindr")
/automount/home/jcampbell/tools/itc/trfind.sh: line 16: [[: /trfindr: syntax error: operand expected (error token is "/trfindr")
/automount/home/jcampbell/tools/itc/trfind.sh: line 20: [[: /trfindr: syntax error: operand expected (error token is "/trfindr")
/automount/home/jcampbell/tools/itc/trfind.sh: line 24: [[: /trfindr: syntax error: operand expected (error token is "/trfindr")
/automount/home/jcampbell/tools/itc/trfind.sh: line 28: [[: /trfindr: syntax error: operand expected (error token is "/trfindr")
這是工作腳本。這只是&的教育自己。我很高興收到各種答案。
#!/bin/bash
touch ~/trfindlog.txt
echo $1 > ~/trfindlog.txt
varR=$(echo $1 | tr -cd r)
varT=$(echo $1 | tr -cd t)
if [[ "${#varR}" -eq 0 && "${#varT}" -eq 0 ]]
then
echo "This phrase contains no Rs or Ts."
elif [[ "${#varR}" -eq 1 && "${#varT}" -eq 1 ]]
then
echo "This phrase contains 1 R and 1 T."
elif [[ "${#varR}" -gt 1 && "${#varT}" -eq 1 ]]
then
echo "This phrase contains ${#varR} Rs and 1 T."
elif [[ "${#varR}" -eq 1 && "${#varT}" -gt 1 ]]
then
echo "This phrase contains 1 R and ${#varT} Ts."
elif [[ "${#varR}" -gt 1 && "${#varT}" -gt 1 ]]
then
echo "This phrase contains ${#varR} Rs and ${#varT} Ts."
fi
rm ~/trfindlog.txt
exit
直接的問題是,您將文件名,而不是其內容,分配給您獲取錯誤的變量。 – tripleee
如果它不熟悉,你可以得到像'rcount = $(grep -oi'r'<<<「$ 1」| wc -l)' – tripleee