bash Shell脚本将文件内容与字符串进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39259528/
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 compare file content with a string
提问by ashutosh tripathi
I have a String "ABCD" and a file test.txt. I want to check if the file has only this content "ABCD". Usually I get the file with "ABCD" only and I want to send email notifications when I get anything else apart from this string so I want to check for this condition. Please help!
我有一个字符串“ABCD”和一个文件 test.txt。我想检查文件是否只有这个内容“ABCD”。通常我只得到带有“ABCD”的文件,当我得到除此字符串之外的任何其他内容时,我想发送电子邮件通知,因此我想检查这种情况。请帮忙!
回答by chepner
Update: My original answer would unnecessarily read a large file into memory when it couldn't possibly match. Any multi-line file would fail, so you only need to read two lines at most. Instead, read the first line. If it does not match the string, orif a second read
succeeds at all, regardless of what it reads, then send the e-mail.
更新:当大文件不可能匹配时,我的原始答案会不必要地将大文件读入内存。任何多行文件都会失败,因此您最多只需要读取两行。相反,请阅读第一行。如果它与字符串不匹配,或者如果一秒钟完全read
成功,无论读取的是什么,然后发送电子邮件。
str=ABCD
if { IFS= read -r line1 &&
[[ $line1 != $str ]] ||
IFS= read -r $line2
} < test.txt; then
# send e-mail
fi
Just read in the entire file and compare it to the string:
只需读入整个文件并将其与字符串进行比较:
str=ABCD
if [[ $(< test.txt) != "$str" ]]; then
# send e-mail
fi
回答by NickD
Something like this should work:
这样的事情应该工作:
s="ABCD"
if [ "$s" == "$(cat test.txt)" ] ;then
:
else
echo "They don't match"
fi
回答by Scott Wang
str="ABCD"
content=$(cat test.txt)
if [ "$str" == "$content" ];then
# send your email
fi
回答by sachin_ur
if [ "$(cat test.tx)" == ABCD ]; then
# send your email
else
echo "Not matched"
fi