如何查找字符串是否包含在具有文件内容的变量上?

时间:2019-06-13 15:13:30

标签: bash shell scripting grep

在包含文件内容的变量上找不到特定的字符串

sumifs

我希望输出“ Found”或“ Not Found”,但最终会显示错误

1 个答案:

答案 0 :(得分:1)

如果要将文件存储到变量中然后运行grep,则此方法有点多余:

#!/bin/bash

core_pattern=$(cat /proc/sys/kernel/core_pattern)
apport_full_path="/usr/share/apport/apport"


if  grep -q "$apport_full_path" <<< "$core_pattern"  ; then
   echo "Found"
else
   echo "Not Found"
fi

或者,更好的是,对文件本身运行grep,为什么要存储到变量中:

#!/bin/bash

pattern_file="/proc/sys/kernel/core_pattern"
apport_full_path="/usr/share/apport/apport"


if  grep -q "$apport_full_path" "$pattern_file"  ; then
   echo "Found"
else
   echo "Not Found"
fi

通常grep的用法如下:

grep <string to search> <file_to_seaarch>

grep <string_to_Search> <<< "${variable_to_search}"