我正在构建一个脚本来计算给定字符串中两个字母的出现次数。我无法弄清楚如何使变量成为一个可测试的数字。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