Eliminar archivos con cadena encontrada en file-linux cli


Estoy tratando de eliminar correos electrónicos erróneos basados en encontrar la dirección de correo electrónico en el archivo a través de Linux CLI.

Puedo obtener los archivos con

find . | xargs grep -l [email protected]

Pero no puedo averiguar cómo eliminarlos desde allí ya que el siguiente código no funciona.

rm -f | xargs find . | xargs grep -l [email protected]

Gracias por su ayuda.

Author: Spechal, 2010-12-25

7 answers

Por seguridad, normalmente canalizo la salida de find a algo como awk y creo un archivo por lotes con cada línea siendo "rm filename"

De esa manera puede comprobarlo antes de ejecutarlo y corregir manualmente cualquier caso de borde impar que sea difícil de hacer con una expresión regular

find . | xargs grep -l [email protected] | awk '{print "rm "$1}' > doit.sh
vi doit.sh // check for murphy and his law
source doit.sh
 53
Author: Martin Beckett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-29 17:52:07

@Martin Beckett publicó una excelente respuesta, por favor siga esa directriz

Solución para su comando :

grep -l [email protected] * | xargs rm

O

for file in $(grep -l [email protected] *); do
    rm -i $file;
    #  ^ prompt for delete
done
 57
Author: ajreal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-06 19:59:15

Puede usar find's -exec y -delete, solo eliminará el archivo si el comando grep tiene éxito. Usando grep -q para que no imprima nada, puede reemplazar el -q con -l para ver qué archivos tenían la cadena en ellos.

find . -exec grep -q '[email protected]' '{}' \; -delete
 13
Author: OneOfOne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-17 21:20:55

A pesar de la respuesta segura de Martin, si tienes certeza de lo que quieres eliminar, como al escribir un script, he usado esto con mayor éxito que cualquier otro texto sugerido antes por aquí:

$ find . | grep -l [email protected] | xargs -I {} rm -rf {}

Pero prefiero encontrar por nombre:

$ find . -iname *something* | xargs -I {} echo {}
 2
Author: cregox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-08 23:40:12

Me gustó la solución de Martin Beckett, pero encontré que los nombres de archivo con espacios podrían complicarlo (como who uses spaces in file names, pfft :D). También quería revisar qué coincidía, así que muevo los archivos coincidentes a una carpeta local en lugar de simplemente eliminarlos con el comando' rm':

# Make a folder in the current directory to put the matched files
$ mkdir -p './matched-files'

# Create a script to move files that match the grep
# NOTE: Remove "-name '*.txt'" to allow all file extensions to be searched.
# NOTE: Edit the grep argument 'something' to what you want to search for.

$ find . -name '*.txt' -print0 | xargs -0 grep -al 'something' | awk -F '\n' '{ print "mv \""$0"\" ./matched-files" }' > doit.sh

Or because its possible (in Linux, idk about other OS's) to have newlines in a file name you can use this longer, untested if works better (who puts newlines in filenames? pfft :D), version:

$ find . -name '*.txt' -print0 | xargs -0 grep -alZ 'something' | awk -F '\0' '{ for (x=1; x<NF; x++) print "mv \""$x"\" ./matched-files" }' > doit.sh

# Evaluate the file following the 'source' command as a list of commands executed in the current context:
$ source doit.sh

NOTA: Tuve problemas en los que grep no podía coincidir con archivos que tenían codificación utf-16. Vea aquí para una solución alternativa. En caso de que ese sitio web desaparezca lo que haces es usar grep's-a flag lo que hace que grep trate los archivos como texto y use un patrón de expresiones regulares que coincida con cualquier primer byte en cada carácter extendido. Por ejemplo, para que coincida con Entité hacer esto:

grep -a 'Entit.e'

Y si eso no funciona entonces prueba esto:

grep -a 'E.n.t.i.t.e'
 1
Author: FocusedWolf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-23 18:08:04
find . | xargs grep -l [email protected]

Cómo eliminar:

rm -f 'find . | xargs grep -l [email protected]'
 0
Author: marian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-14 10:05:31
rm -f `find . | xargs grep -li [email protected]`

Hace el trabajo mejor. Utilizar `...'para ejecutar el comando para ofrecer los nombres de archivo que contienen [email protected] (grep-l los enumera, - i ignora el caso) para eliminarlos con rm (-f forzosamente / -i interactivamente).

 0
Author: Kastor Stein,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-06 08:43:45