我想在一个文件中搜索一个字符串,在这个网站上搜索了很多次之后,我最终使用了grep
in 和if
语句。然而,事情并没有像我期望的那样工作,即使我遵循了我在其他相关帖子中找到的所有说明。这是我的代码。
echo "Enter dicounter number"
read string1
echo "Enter side with LEDs"
read string2
if grep -q "dicounter_$string1_from_$string2" MasterFile.txt; then
echo "dicounter_$string1_from$string2 already exists in MasterFile."
else
{ (a bunch of stuff to make the transmitter operate) }
fi
Run Code Online (Sandbox Code Playgroud)
我认为的主要问题是我在命令行参数中的阅读方式。
如果脚本没有按预期工作,您可能想要尝试的第一件事是set -x
在代码中的麻烦位置之前添加(在本例中,在 之前grep
),然后运行脚本。然后您将看到脚本实际在做什么,以便您可以将其与您期望它做的事情进行比较。
在您的情况下,问题可能是_
变量名称中的有效字符,因此您尝试使用的值$string1_from_
而不是$string1
您期望的值。这就是为什么即使不使用花哨的操作,将变量名括在花括号中也是一种很好的做法。例如:
if grep -q "dicounter_${string1}_from_${string2}" MasterFile.txt; then
echo "dicounter_${string1}_from${string2} already exists in MasterFile."
else
[..]
Run Code Online (Sandbox Code Playgroud)