Check If File Contains String

How to check if a file contains a specific string using Bash

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

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.

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

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 [[]].

how to check if text file contains string?

You don't need looping 'cause your file is just text, so just use conditional

with open("test.txt","r") as f:
content = f.read()
if 'banana' in content:
do_something()
else:
exit()

Bash script - Check if a file contains a specific line

if $FILE contains the file name and $STRING contains the string to be searched,
then you can display if the file matches using the following command:

if [ ! -z $(grep "$STRING" "$FILE") ]; then echo "FOUND"; fi

Determine if a file contains a string in C

This reads a file line by line and checks if the line matches the string supplied in argument 1 (argv[1]) after every read. If so, it sets the bool infile (bools defined in <stdbool.h>) to true.

#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv[]) {
char *filepath = "/path/to/file";
bool infile = false;
char *line = NULL;
size_t len = 0;
ssize_t read;

FILE *fp = fopen(filepath, "r");

if (!fp) {
fprintf(stderr, "Failed to open %s\n", filepath);
return 1;
}

while ((read = getline(&line, &len, fp)) != -1) {
line[strcspn(line, "\n")] = 0;
if (!strcmp(line, argv[1])) {
infile = true;
break;
}
}
fclose(uuidfp);

if (line)
free(line);

return 0;
}

How to check if a file contains a string and nothing else

You can still use diff (or cmp, if you don't need an accounting of the differences). All you need to do is either create or "fake" a file that contains the string you want to compare with. There are several ways to do that:

  • Send the string to diff or cmp on standard input using a "here string" designated by <<<, and use - as an argument to let the program know it should be reading from stdin:

    $ cmp filename - <<<"Hello World"

    (note that there will be no trailing newline on the "Hello World" passed in this way, unlike some other suggestions below)

  • For longer strings that may contain newlines, same thing except use a "here document" introduced by <<

    $ cmp filename - <<EOF
    Hello World
    and here is another line
    EOF

    (note the EOF can be anything, just make sure it's the same at the beginning and end)

  • Write the string to a temporary file and use that as the comparison

    $ TMPFILE=$(mktemp)
    $ echo "Hello World" > "$TMPFILE"
    $ cmp filename "$TMPFILE"
    $ rm "$TMPFILE"
  • Pipe the string to standard input of the comparison program

    $ echo "Hello World" | cmp filename -
  • Create a "fake" file that will provide the desired text to the comparison program using process substitution

    $ cmp filename <(echo "Hello World")

How to test if string exists in file with Bash?

grep -Fxq "$FILENAME" my_list.txt

The exit status is 0 (true) if the name was found, 1 (false) if not, so:

if grep -Fxq "$FILENAME" my_list.txt
then
# code if found
else
# code if not found
fi

Explanation

Here are the relevant sections of the man page for grep:

grep [options] PATTERN [FILE...]

-F, --fixed-strings

        Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.

-x, --line-regexp

        Select only those matches that exactly match the whole line.

-q, --quiet, --silent

        Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option.

Error handling

As rightfully pointed out in the comments, the above approach silently treats error cases as if the string was found. If you want to handle errors in a different way, you'll have to omit the -q option, and detect errors based on the exit status:

Normally, the exit status is 0 if selected lines are found and 1 otherwise. But the exit status is 2 if an error occurred, unless the -q or --quiet or --silent option is used and a selected line is found. Note, however, that POSIX only mandates, for programs such as grep, cmp, and diff, that the exit status in case of error be greater than 1; it is therefore advisable, for the sake of portability, to use logic that tests for this general condition instead of strict equality with 2.

To suppress the normal output from grep, you can redirect it to /dev/null. Note that standard error remains undirected, so any error messages that grep might print will end up on the console as you'd probably want.

To handle the three cases, we can use a case statement:

case `grep -Fx "$FILENAME" "$LIST" >/dev/null; echo $?` in
0)
# code if found
;;
1)
# code if not found
;;
*)
# code if an error occurred
;;
esac

To check whether particular string is present in text file using robotframework

You can put the content of the file in a string and then check for the string presence in the string:

${my_string}    Get File    C:/path/to/my_file.txt
Should Contain ${my_string} Status:true


Related Topics



Leave a reply



Submit