如何使用 Bash 检查文件是否包含特定字符串 [英] How to check if a file contains a specific string using Bash

查看:38
本文介绍了如何使用 Bash 检查文件是否包含特定字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 bash 中检查文件是否包含特定字符串.我使用了这个脚本,但它不起作用:

I want to check if a file contains a specific string or not in bash. I used this script, but it doesn't work:

 if [[ 'grep 'SomeString' $File' ]];then
   # Some Actions
 fi

我的代码有什么问题?

推荐答案

if grep -q SomeString "$File"; then
  Some Actions # SomeString was found
fi

这里不需要 [[ ]].直接运行命令就行了.当您不需要找到时显示的字符串时,添加 -q 选项.

You don't need [[ ]] here. Just run the command directly. Add -q option when you don't need the string displayed when it was found.

grep 命令在退出代码中返回 0 或 1,具体取决于搜索的结果.0 如果找到了一些东西;1 否则.

The grep command returns 0 or 1 in the exit code depending on the result of search. 0 if something was found; 1 otherwise.

$ echo hello | grep hi ; echo $?
1
$ echo hello | grep he ; echo $?
hello
0
$ echo hello | grep -q he ; echo $?
0

你可以指定命令作为if的条件.如果命令在其退出代码中返回 0,则表示条件为真;否则为假.

You can specify commands as an condition of if. If the command returns 0 in its exitcode that means that the condition is true; otherwise false.

$ if /bin/true; then echo that is true; fi
that is true
$ if /bin/false; then echo that is true; fi
$

如您所见,您可以直接在此处运行程序.没有额外的 [][[]].

As you can see you run here the programs directly. No additional [] or [[]].

这篇关于如何使用 Bash 检查文件是否包含特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆