groovyjenkins-groovygroovyshellgroovy-console

How to check all files in a directory except one file in Groovy language


I am trying to search a word in every file in a directory but I want to exclude my logfile.

My code is something like this

user input: search test C:\Users\Desktop\test\Groovy


My code

import static groovy.io.FileType.FILES
import java.text.SimpleDateFormat

def terminal_log = new File("terminal.log")
def terminal_log_path = terminal_log.getName()
def fas = ""
def file2_path = ""
def cmd = System.console().readLine 'Enter command: '
String[] csplice = cmd.split(" ");
if(csplice.length == 3){
    def first_parameter = csplice[0]
    def second_parameter = csplice[1]
    def third_parameter = csplice[2]
    if(first_parameter == "search"){
        def file = new File(third_parameter)
        if(file.exists()){
            if(file.isDirectory()){
                file.eachFile(FILES) { f -> 
                    fas = "/"+f+"/"
                    File file2 = new File(fas)
                    file2_path = file2.getName()
                    if(!file2_path == terminal_log_path){
                        file2.eachLine{ line ->
                            if(line.contains(second_parameter)){
                                println "This file contains this word"
                            }
                        }
                    }
                }
            }else{
                println "Not a directory"
            }
        }else{
            println "Not exists"
        }
    }else{
        println "Invalid command"
    }
}else{
    println "Invalid command"
}

This block here is not working

if(!file2_path == terminal_log_path){

Is there any documentation that I can read to exclude a specific file while checking every files in a directory?

Many thanks

EDIT: the directory of the user input has the logfile (terminal.log) terminal.log exists


Solution

  • It should be:

    if (file2_path != terminal_log_path) {
       ...
    }
    

    or

    if (!(file2_path == terminal_log_path)) {
       ...
    }
    

    E.g. you can run the following code to see the result of applying the "Not" operator to a string in Groovy:

    def file2_path = "/i/am/path/"
    println (!file2_path) // prints false as file2_path is not an empty string
    

    For more info, you can refer to the official Groovy doc on that topic:

    The "not" operator is represented with an exclamation mark (!) and inverts the result of the underlying boolean expression. In particular, it is possible to combine the not operator with the Groovy truth:

        assert (!true)    == false
        assert (!'foo')   == false
        assert (!'')      == true