Eliminar todos los archivos, ¡pero mantenga a todos los directorios en un script de bash? -- bash campo con shell camp Relacionados El problema

Delete all files but keep all directories in a bash script?


22
vote

problema

Español

Estoy tratando de hacer algo que probablemente sea muy simple, tengo una estructura de directorios, como:

  dir/     subdir1/     subdir2/         file1         file2         subsubdir1/             file3   

Me gustaría ejecutar un comando en un script de bash que eliminará todos los archivos recursivamente desde la dirección, pero deje todos los directorios. Es decir:

  dir/     subdir1/     subdir2/         subsubdir1   

¿Cuál sería un comando adecuado para esto?

Original en ingles

I'm trying to do something which is probably very simple, I have a directory structure such as:

dir/     subdir1/     subdir2/         file1         file2         subsubdir1/             file3 

I would like to run a command in a bash script that will delete all files recursively from dir on down, but leave all directories. Ie:

dir/     subdir1/     subdir2/         subsubdir1 

What would be a suitable command for this?

     

Lista de respuestas

42
 
vote
vote
La mejor respuesta
 
  find dir -type f -print0 | xargs -0 rm   

find Enumera todos los archivos que coinciden con cierta expresión en un directorio determinado, recursivamente. -type f coincide con los archivos regulares. -print0 es para imprimir nombres usando WinRing0x64.sys0 como delimitador (como cualquier otro carácter, incluido WinRing0x64.sys1111 , podría estar en un nombre de ruta). WinRing0x64.sys2 es para reunir los nombres de archivos de la entrada estándar y ponerlos como parámetros. WinRing0x64.sys3 es para asegurarse de que WinRing0x64.sys4 entenderá el WinRing0x64.sys5 delimitador.

WinRing0x64.sys6 es lo suficientemente sabio como para llamar WinRing0x64.sys7 varias veces si la lista de parámetros se pondría demasiado grande. Así que es mucho mejor que tratar de llamar a STH. Como WinRing0x64.sys8 . También es mucho más rápido que llamar WinRing0x64.sys9 para cada archivo por sí mismo, como private static bool ExtractDriver(string fileName) { string resourceName = "OpenHardwareMonitor.Hardware." + (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" : "WinRing0.sys"); string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); byte[] buffer = null; for (int i = 0; i < names.Length; i++) { if (names[i].Replace('\', '.') == resourceName) { using (Stream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream(names[i])) { buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); } } } if (buffer == null) return false; try { using (FileStream target = new FileStream(fileName, FileMode.Create)) { target.Write(buffer, 0, buffer.Length); target.Flush(); } } catch (IOException) { // for example there is not enough space on the disk return false; } // make sure the file is actually writen to the file system for (int i = 0; i < 20; i++) { try { if (File.Exists(fileName) && new FileInfo(fileName).Length == buffer.Length) { return true; } Thread.Sleep(100); } catch (IOException) { Thread.Sleep(10); } } // file still has not the right size, something is wrong return false; } 0 .

 
find dir -type f -print0 | xargs -0 rm 

find lists all files that match certain expression in a given directory, recursively. -type f matches regular files. -print0 is for printing out names using \0 as delimiter (as any other character, including \n, might be in a path name). xargs is for gathering the file names from standard input and putting them as a parameters. -0 is to make sure xargs will understand the \0 delimiter.

xargs is wise enough to call rm multiple times if the parameter list would get too big. So it is much better than trying to call sth. like rm $((find ...). Also it much faster than calling rm for each file by itself, like find ... -exec rm \{\}.

 
 
10
 
vote

Con el private static bool ExtractDriver(string fileName) { string resourceName = "OpenHardwareMonitor.Hardware." + (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" : "WinRing0.sys"); string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); byte[] buffer = null; for (int i = 0; i < names.Length; i++) { if (names[i].Replace('\', '.') == resourceName) { using (Stream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream(names[i])) { buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); } } } if (buffer == null) return false; try { using (FileStream target = new FileStream(fileName, FileMode.Create)) { target.Write(buffer, 0, buffer.Length); target.Flush(); } } catch (IOException) { // for example there is not enough space on the disk return false; } // make sure the file is actually writen to the file system for (int i = 0; i < 20; i++) { try { if (File.Exists(fileName) && new FileInfo(fileName).Length == buffer.Length) { return true; } Thread.Sleep(100); } catch (IOException) { Thread.Sleep(10); } } // file still has not the right size, something is wrong return false; } 1 puede usar el private static bool ExtractDriver(string fileName) { string resourceName = "OpenHardwareMonitor.Hardware." + (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" : "WinRing0.sys"); string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); byte[] buffer = null; for (int i = 0; i < names.Length; i++) { if (names[i].Replace('\', '.') == resourceName) { using (Stream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream(names[i])) { buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); } } } if (buffer == null) return false; try { using (FileStream target = new FileStream(fileName, FileMode.Create)) { target.Write(buffer, 0, buffer.Length); target.Flush(); } } catch (IOException) { // for example there is not enough space on the disk return false; } // make sure the file is actually writen to the file system for (int i = 0; i < 20; i++) { try { if (File.Exists(fileName) && new FileInfo(fileName).Length == buffer.Length) { return true; } Thread.Sleep(100); } catch (IOException) { Thread.Sleep(10); } } // file still has not the right size, something is wrong return false; } 2 Acción:

  private static bool ExtractDriver(string fileName) {   string resourceName = "OpenHardwareMonitor.Hardware." +     (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" :      "WinRing0.sys");    string[] names =     Assembly.GetExecutingAssembly().GetManifestResourceNames();   byte[] buffer = null;   for (int i = 0; i < names.Length; i++) {     if (names[i].Replace('\', '.') == resourceName) {       using (Stream stream = Assembly.GetExecutingAssembly().         GetManifestResourceStream(names[i]))        {           buffer = new byte[stream.Length];           stream.Read(buffer, 0, buffer.Length);       }     }   }    if (buffer == null)     return false;    try {     using (FileStream target = new FileStream(fileName, FileMode.Create)) {       target.Write(buffer, 0, buffer.Length);       target.Flush();     }   } catch (IOException) {      // for example there is not enough space on the disk     return false;    }    // make sure the file is actually writen to the file system   for (int i = 0; i < 20; i++) {     try {       if (File.Exists(fileName) &&         new FileInfo(fileName).Length == buffer.Length)        {         return true;       }       Thread.Sleep(100);     } catch (IOException) {       Thread.Sleep(10);     }   }    // file still has not the right size, something is wrong   return false; } 3  

con el estándar private static bool ExtractDriver(string fileName) { string resourceName = "OpenHardwareMonitor.Hardware." + (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" : "WinRing0.sys"); string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); byte[] buffer = null; for (int i = 0; i < names.Length; i++) { if (names[i].Replace('\', '.') == resourceName) { using (Stream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream(names[i])) { buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); } } } if (buffer == null) return false; try { using (FileStream target = new FileStream(fileName, FileMode.Create)) { target.Write(buffer, 0, buffer.Length); target.Flush(); } } catch (IOException) { // for example there is not enough space on the disk return false; } // make sure the file is actually writen to the file system for (int i = 0; i < 20; i++) { try { if (File.Exists(fileName) && new FileInfo(fileName).Length == buffer.Length) { return true; } Thread.Sleep(100); } catch (IOException) { Thread.Sleep(10); } } // file still has not the right size, something is wrong return false; } 4 puede usar private static bool ExtractDriver(string fileName) { string resourceName = "OpenHardwareMonitor.Hardware." + (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" : "WinRing0.sys"); string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); byte[] buffer = null; for (int i = 0; i < names.Length; i++) { if (names[i].Replace('\', '.') == resourceName) { using (Stream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream(names[i])) { buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); } } } if (buffer == null) return false; try { using (FileStream target = new FileStream(fileName, FileMode.Create)) { target.Write(buffer, 0, buffer.Length); target.Flush(); } } catch (IOException) { // for example there is not enough space on the disk return false; } // make sure the file is actually writen to the file system for (int i = 0; i < 20; i++) { try { if (File.Exists(fileName) && new FileInfo(fileName).Length == buffer.Length) { return true; } Thread.Sleep(100); } catch (IOException) { Thread.Sleep(10); } } // file still has not the right size, something is wrong return false; } 5 :

  private static bool ExtractDriver(string fileName) {   string resourceName = "OpenHardwareMonitor.Hardware." +     (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" :      "WinRing0.sys");    string[] names =     Assembly.GetExecutingAssembly().GetManifestResourceNames();   byte[] buffer = null;   for (int i = 0; i < names.Length; i++) {     if (names[i].Replace('\', '.') == resourceName) {       using (Stream stream = Assembly.GetExecutingAssembly().         GetManifestResourceStream(names[i]))        {           buffer = new byte[stream.Length];           stream.Read(buffer, 0, buffer.Length);       }     }   }    if (buffer == null)     return false;    try {     using (FileStream target = new FileStream(fileName, FileMode.Create)) {       target.Write(buffer, 0, buffer.Length);       target.Flush();     }   } catch (IOException) {      // for example there is not enough space on the disk     return false;    }    // make sure the file is actually writen to the file system   for (int i = 0; i < 20; i++) {     try {       if (File.Exists(fileName) &&         new FileInfo(fileName).Length == buffer.Length)        {         return true;       }       Thread.Sleep(100);     } catch (IOException) {       Thread.Sleep(10);     }   }    // file still has not the right size, something is wrong   return false; } 6  
 

With GNU's find you can use the -delete action:

find dir -type f -delete 

With standard find you can use -exec rm:

find dir -type f -exec rm {} + 
 
 
8
 
vote
  private static bool ExtractDriver(string fileName) {   string resourceName = "OpenHardwareMonitor.Hardware." +     (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" :      "WinRing0.sys");    string[] names =     Assembly.GetExecutingAssembly().GetManifestResourceNames();   byte[] buffer = null;   for (int i = 0; i < names.Length; i++) {     if (names[i].Replace('\', '.') == resourceName) {       using (Stream stream = Assembly.GetExecutingAssembly().         GetManifestResourceStream(names[i]))        {           buffer = new byte[stream.Length];           stream.Read(buffer, 0, buffer.Length);       }     }   }    if (buffer == null)     return false;    try {     using (FileStream target = new FileStream(fileName, FileMode.Create)) {       target.Write(buffer, 0, buffer.Length);       target.Flush();     }   } catch (IOException) {      // for example there is not enough space on the disk     return false;    }    // make sure the file is actually writen to the file system   for (int i = 0; i < 20; i++) {     try {       if (File.Exists(fileName) &&         new FileInfo(fileName).Length == buffer.Length)        {         return true;       }       Thread.Sleep(100);     } catch (IOException) {       Thread.Sleep(10);     }   }    // file still has not the right size, something is wrong   return false; } 7  
 
find dir -type f -exec rm '{}' + 
 
 
 
 
8
 
vote
  private static bool ExtractDriver(string fileName) {   string resourceName = "OpenHardwareMonitor.Hardware." +     (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" :      "WinRing0.sys");    string[] names =     Assembly.GetExecutingAssembly().GetManifestResourceNames();   byte[] buffer = null;   for (int i = 0; i < names.Length; i++) {     if (names[i].Replace('\', '.') == resourceName) {       using (Stream stream = Assembly.GetExecutingAssembly().         GetManifestResourceStream(names[i]))        {           buffer = new byte[stream.Length];           stream.Read(buffer, 0, buffer.Length);       }     }   }    if (buffer == null)     return false;    try {     using (FileStream target = new FileStream(fileName, FileMode.Create)) {       target.Write(buffer, 0, buffer.Length);       target.Flush();     }   } catch (IOException) {      // for example there is not enough space on the disk     return false;    }    // make sure the file is actually writen to the file system   for (int i = 0; i < 20; i++) {     try {       if (File.Exists(fileName) &&         new FileInfo(fileName).Length == buffer.Length)        {         return true;       }       Thread.Sleep(100);     } catch (IOException) {       Thread.Sleep(10);     }   }    // file still has not the right size, something is wrong   return false; } 8  

donde dir es el nivel superior de donde desea eliminar archivos de

Tenga en cuenta que esto eliminará solo archivos regulares, no enlaces simbólicos, no dispositivos, etc. Si desea eliminar todo, excepto los directorios, use

  private static bool ExtractDriver(string fileName) {   string resourceName = "OpenHardwareMonitor.Hardware." +     (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" :      "WinRing0.sys");    string[] names =     Assembly.GetExecutingAssembly().GetManifestResourceNames();   byte[] buffer = null;   for (int i = 0; i < names.Length; i++) {     if (names[i].Replace('\', '.') == resourceName) {       using (Stream stream = Assembly.GetExecutingAssembly().         GetManifestResourceStream(names[i]))        {           buffer = new byte[stream.Length];           stream.Read(buffer, 0, buffer.Length);       }     }   }    if (buffer == null)     return false;    try {     using (FileStream target = new FileStream(fileName, FileMode.Create)) {       target.Write(buffer, 0, buffer.Length);       target.Flush();     }   } catch (IOException) {      // for example there is not enough space on the disk     return false;    }    // make sure the file is actually writen to the file system   for (int i = 0; i < 20; i++) {     try {       if (File.Exists(fileName) &&         new FileInfo(fileName).Length == buffer.Length)        {         return true;       }       Thread.Sleep(100);     } catch (IOException) {       Thread.Sleep(10);     }   }    // file still has not the right size, something is wrong   return false; } 9  
 
find dir -type f -exec rm {} \; 

where dir is the top level of where you want to delete files from

Note that this will only delete regular files, not symlinks, not devices, etc. If you want to delete everything except directories, use

find dir -not -type d -exec rm {} \; 
 
 
 
 

Relacionados problema

21  Linux Shell equivalente en IIS  ( Linux shell equivalent on iis ) 
Como desarrollador de lámparas, considerando mudarse a una plataforma .NET IIS, una de mis inquietudes es la pérdida de productividad debido a la falta de she...

1  ¿Para qué se usa la opción Korn Typset (TAG)?  ( What is the korn typset option t tag used for ) 
Estaba leyendo sobre el korn Comando tiposet y descubierto la opción -t agrega una etiqueta, pero no puedo averiguar para qué se usa. ¿Alguien tiene un ej...

1133  Cómo llamar a los comandos de Shell de Ruby  ( How to call shell commands from ruby ) 
¿Cómo llamo los comandos de Shell desde el interior de un programa de rubí? ¿Cómo obtengo la salida de estos comandos de vuelta a Ruby? ...

19  Abra un búfer de emacs cuando un comando intenta abrir un editor en modo shell  ( Open an emacs buffer when a command tries to open an editor in shell mode ) 
Me gusta usar el modo Shell de Emacs, pero tiene algunas deficiencias. Uno de esos es que no es lo suficientemente inteligente como para abrir un nuevo búfer ...

22  Shell Scripting Entrada Redirección Oddies  ( Shell scripting input redirection oddities ) 
¿Puede alguien explicar este comportamiento? Corriendo: #!/bin/sh echo "hello world" | read var1 var2 echo $var1 echo $var2 Resultados en nada siendo O...

0  ¿Es una mala práctica deshabilitar las "características" basadas en el sistema operativo?  ( Is it bad practice to disable os based features ) 
Una cosa que no puedo obtener mi cabeza es el interrogatorio persistente aquí, y en otros lugares de la web, sobre la desactivación de las "características" b...

55  Calcular el tamaño de los archivos en Shell  ( Calculate size of files in shell ) 
Estoy tratando de calcular el tamaño total en bytes de todos los archivos (en un árbol de directorios) que coincide con un patrón de nombre de archivo solo co...

271  ¿Cómo encontrar si una variable está vacía o no en Bash?  ( How to find whether or not a variable is empty in bash ) 
¿Cómo puedo verificar si una variable está vacía en Bash? ...

5  Compruebe el nombre de usuario y la contraseña de UNIX en un shellscript  ( Check unix username and password in a shellscript ) 
Quiero verificar en un script de shell si un nombre de usuario y contraseña pasados ​​de un usuario local son correctos. ¿Cuál es la forma más fácil de hacer ...

41  ¿Hay buenas bibliotecas de Java que faciliten la construcción de aplicaciones de línea de comandos? [cerrado]  ( Are there good java libraries that facilitate building command line applications ) 
cerrado. Esta pregunta no cumple con pautas de desbordamiento de pila . Actualmente no está aceptando respuestas. ...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos