【问题标题】:How to find if string contain on the variable which has contents of file?如何查找字符串是否包含在具有文件内容的变量中?
【发布时间】:2019-06-13 15:13:30
【问题描述】:
在包含文件内容的变量上找不到特定字符串
#!/bin/bash
core_pattern=$(cat /proc/sys/kernel/core_pattern)
apport_full_path="/usr/share/apport/apport"
if [[ $(grep "$apport_full_path" "$core_pattern") ]] ; then
echo "Found"
else
echo "Not Found"
fi
grep: |/usr/share/apport/apport %p %s %c %d %P: No such file or directory
Not Found
我希望输出“找到”或“未找到”但最终出现错误
【问题讨论】:
标签:
bash
shell
scripting
grep
【解决方案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}"