Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use grep to find content in files and move them if they match

I'm using grep to generate a list of files I need to move:

grep -L -r 'Subject: \[SPAM\]' . 

How can I pass this list to the mv command and move the files somewhere else?

like image 949
user17582 Avatar asked Sep 18 '08 12:09

user17582


People also ask

How do I move grep results?

If you want to "clean" the results you can filter them using pipe | for example: grep -n "test" * | grep -v "mytest" > output-file will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v ) - and will redirect the result to an output file.

How do I use grep to search inside files?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.

How do you grep after match?

To also show you the lines before your matches, you can add -B to your grep. The -B 4 tells grep to also show the 4 lines before the match. Alternatively, to show the log lines that match after the keyword, use the -A parameter. In this example, it will tell grep to also show the 2 lines after the match.


2 Answers

If you want to find and move files that do not match your pattern (move files that don't contain 'Subject \[SPAM\]' in this example) use:

grep -L -Z -r 'Subject: \[SPAM\]' . | xargs -0 -I{} mv {} DIR 

The -Z means output with zeros (\0) after the filenames (so spaces are not used as delimeters).

xargs -0 

means interpret \0 to be delimiters.

The -L means find files that do not match the pattern. Replace -L with -l if you want to move files that match your pattern.

Then

-I{} mv {} DIR 

means replace {} with the filenames, so you get mv filenames DIR.

like image 134
daveb Avatar answered Oct 03 '22 00:10

daveb


This alternative works where xargs is not availabe:

grep -L -r 'Subject: \[SPAM\]' . | while read f; do mv "$f" out; done 
like image 20
Tobias Kunze Avatar answered Oct 02 '22 23:10

Tobias Kunze