programmer
programmer

Reputation: 31

How to list strings that are not found in a folder using unix

I have a list of strings in a text file . The source folder has some files which contains the string. If a string is found in the source folder, I am copying it to a target folder.

srcdirectory - source directory to check if the strings are present.
stringList.txt - list of strings to test.
target - copy found strings to this folder.

For example,
srcdirectory has files :

a.edi (contains string 'a' in the content of the file)                                                                                      
b.edi (contains string 'b' in the content of the file)                   
c.edi (contains string 'c' in the content of the file)                                                                                                                                                                                                                                                                                      
d.edi (contains string 'd' in the content of the file)                        
e.edi (contains string 'e' in the content of the file)   
f.edi (contains string 'f' in the content of the file) 
g.edi (contains string 'g' in the content of the file

stringList.txt has strings:

a              
b      
c           
d           
e
f
g

If a match is found for the string, it copies the matched file name to the target folder. So target folder contains matched filenames as:

 a.edi            
 c.edi           
 g.edi

Now, I want the unmatched string list to be copied to a different folder as the one below. How do I do that?

    b
    d
    e
    f

Here is my script for matched string:

find srcdirectory/ -maxdepth 2 -type f -exec grep -Ril -f stringList.txt {} \; -exec cp -i {} /home/Rose/target \;

Any help would be appreciated..

Upvotes: 3

Views: 132

Answers (1)

kojiro
kojiro

Reputation: 77137

In general you can do an inverse operation in find with the -o operator:

find srcdirectory -maxdepth 2 -type f \( \
    -exec grep -qif stringList.txt {} \; -exec cp -i {} /home/Rani/target \; \
     \) -o -exec cp -i {} /home/Rani/nonmatches \;

The trick here is that the parenthesized expression has to be "true" (success/0 exit status) for files that match, and false otherwise. If the cp -i can fail for matched files, this will be imprecise. If that's a possibility you're concerned about, you would need to capture the status of grep -q and re-apply it after the cp expression.

Perhaps it's just easier to drop into bash.

find srcdirectory -maxdepth 2 -type f -exec bash -c '
    for file; do
        if grep -qif stringList.txt "$file"; then
            cp -i "$file" /home/Rani/target
        else
            cp -i "$file" /home/Rani/nonmatches
        fi
    done
' _ {} +

Upvotes: 1

Related Questions