To check if a file contains a string in Groovy, you can use the contains()
method on the file's text
property. Here's an example:
Check if File Contains a String in Groovy Examples
def fileName = "myfile.txt" def text = "Hello world" new File(fileName).append(text) def str = "Hello world" if (new File(fileName).text.contains(str)) { println "$fileName contains '$str'" } else { println "$fileName does not contain '$str'" }
This code checks if the file myfile.txt
contains the string str
. If it does, it prints "myfile.txt contains 'Hello world'
". If it does not, it prints "myfile.txt does not contain 'Hello world'
".
Here's another example that shows how to check if a file contains a string in a case-insensitive manner:
def fileName = "myfile.txt" def text = "Hello world" new File(fileName).append(text) def str = "Hello world" if (new File(fileName).text.toLowerCase().contains(str.toLowerCase())) { println "$fileName contains '$str' (case-insensitive)" } else { println "$fileName does not contain '$str' (case-insensitive)" }
In this code, we convert both the file's text and the string to lowercase using the toLowerCase()
method. This allows us to check if the file contains the string without considering the case of the characters. If the file contains the string, it prints "myfile.txt contains 'Hello world' (case-insensitive)
". If it does not, it prints "myfile.txt does not contain 'Hello world' (case-insensitive)
".