A good way to clear logs(syslog has a handle on file) which have frozen my linux server(out of space) I tried cat /dev/null > fileABC; cat /dev/null/ > fileXYZ
How can I clear multiple files by cat /dev/null to multiple files in an efficient or single command.
Hard coded solutions
teeEcho nothing and simply send it to multiple files using the
teecommand.Like this:
All files in that list will be empty and created if they don't exist.
Applied to your answer this would be:
While
echo -nis considered better practice thancat /dev/null, an even better solution would be to useprintf '', as noted by Charles Duffy. Resulting in following command:truncateAs answered by skrilled,
truncateis probably the solution you were originally looking for. The command allows arbitrarily many file name arguments to be supplied. You can easily use it as follows:Which allows you to achieve your goal without using any pipe and in a single command, pretty nifty answer supplied here by skrilled.
Structural file names solution
If all files have a structure on their names (for instance java files) and location you could use the find command. In the following example I will apply the erasure to all
.javaand.csource files in the current directory and in all directories inside the current directory.Explained:
find .executefindin current directory.-maxdepth 2recursion level, descend to directories in directory but no further (level 2). Set this to 1 to not descend ornto descendntimes.-type fonly apply to files, not directories-name '*.java'only apply to files ending in.java-exec truncate --size 0 "{}" \;truncate each file found (file name is stored in{})See
man findfor more options and a more detailed explanation. Be sure to check it out becausefindis one of the most powerful tools for automation of file editing.List of files in separate file solution
The easiest thing to do might be to store the files to erase in a file, line by line. If there is no obvious structure with respect to their location and name, that is.
Say the files are stored in a file called
erasure.In this example we will erase three files, which are listed above.
Explanation:
while read filefor each line in the given file, store the line in variablefiledo > "$file"empty the file and output nothing in it (i.e. erase it)done < erasurespecify the input file using<(redirection)Note: while this method preserves spaces in the path, it fails to handle backslashes and trailing white space, as noted by Charles Duffy. One way to fix both issues is to modify the loop as follows:
Yet newlines in file names will still be a problem. The only way around this issue is to separate the file names using null termination (
\0). The correct loop now becomes: