bash shell 脚本 grep 来 grep 一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16468172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
shell script grep to grep a string
提问by Jill448
The output is blank fr the below script. What is it missing? I am trying to grep a string
以下脚本的输出为空白。它缺少什么?我正在尝试 grep 一个字符串
#!/bin/ksh
file=$abc_def_APP_13.4.5.2
if grep -q abc_def_APP $file; then
echo "File Found"
else
echo "File not Found"
fi
回答by Jonathan Leffler
In bash
, use the <<<
redirection from a string (a 'Here string'):
在 中bash
,使用<<<
来自字符串的重定向(a 'Here string'):
if grep -q abc_def_APP <<< $file
In other shells, you may need to use:
在其他 shell 中,您可能需要使用:
if echo $file | grep -q abc_def_APP
I put my then
on the next line; if you want your then
on the same line, then add ; then
after what I wrote.
我把我的then
放在下一行;如果你想then
在同一行,然后; then
在我写的后面加上。
Note that this assignment:
注意这个赋值:
file=$abc_def_APP_13.4.5.2
is pretty odd; it takes the value of an environment variable ${abc_def_APP_13}
and adds .4.5.2
to the end (it must be an env var since we can see the start of the script). You probably intended to write:
很奇怪;它接受环境变量的值${abc_def_APP_13}
并添加.4.5.2
到末尾(它必须是一个环境变量,因为我们可以看到脚本的开头)。你可能打算写:
file=abc_def_APP_13.4.5.2
In general, you should enclose references to variables holding file names in double quotes to avoid problems with spaces etc in the file names. It is not critical here, but good practices are good practices:
通常,您应该用双引号将保存文件名的变量引用括起来,以避免文件名中出现空格等问题。这里并不重要,但好的做法就是好的做法:
if grep -q abc_def_APP <<< "$file"
if echo "$file" | grep -q abc_def_APP
回答by glenn Hymanman
Yuck! Use the shell's string matching
糟糕!使用shell的字符串匹配
if [[ "$file" == *abc_def_APP* ]]; then ...