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!
6 Answers
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, or if a second read succeeds at all, regardless of what it reads, then send the e-mail.
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
2 Comments
Andrei LED
Second option also allows to assert multiline text file content
Andreas Løve Selvik
I had to do
if [[ "$(< test.txt)" != "$str" ]]; then to get the second option to work properly for multiline files. Note the quotes.Something like this should work:
s="ABCD"
if [ "$s" == "$(cat test.txt)" ] ;then
:
else
echo "They don't match"
fi
1 Comment
Paul
$(...) strips trailing carriage return if it exists. Using $(...) works in limited situations. Using cmp as suggested by VasiliNovikov is not only faster, it avoids the use of $(...) which modifies the input stream.
str="ABCD"
content=$(cat test.txt)
if [ "$str" == "$content" ];then
# send your email
fi
1 Comment
Tomas Reimers
I think you may need to add a not to your if statement? The author sounds as if they want to send the email if the contents does not match
if [ "$(cat test.tx)" == ABCD ]; then
# send your email
else
echo "Not matched"
fi
1 Comment
Paul
$(...) strips a trailing carriage return if it exists.
This would be the most efficient and correct solution:
cmp -s -- ./my_file <(echo -n "$my_string")
Full example (verbose):
if cmp --silent -- ./my_file <(printf '%s' "$my_string"); do
echo "File matches the expected string precisely"
fi
Explanation:
- This solution will not trim newlines in the file -- useful if you want a precise test (this was commented below as well, before the edit here)
- The
cmputility will exit early if the file is big, so you don't need to worry about that.
1 Comment
Paul
This is the answer for an exact test. $(...) and read strips trailing newlines which can cause problems.
Solution using grep:
if grep -qe ^$MY_STR$ myfile; then \
echo "success"; \
fi
1 Comment
Lii
This matches for all files where
MY_STR is a sub-string, right? Poster want to match only files where MY_STR is the entire content. ^ and $ is anchors for a line, the the entire file.
cat test.txtand then compare with your string.