4

i have bunch of log files and I have to delete the files of some small sizes, which were erroneous files that got created. ( 63bytes ). I have to copy only those files which have data in it .

3 Answers 3

18

Shell (linux);

find . -type f -size 63c -delete

Will traverse subdirectories (unless you tell it otherwise)

4
  • ~unutbu's addition of a directory is possible, but not needed (defaults to working dir) although it would be nice to illustrate multiple paths can be given: find ./foo/bar ./foz ../../baz -type f would search all 3 directories at once.
    – Wrikken
    Jun 8, 2010 at 0:38
  • 4
    @Wrikken: Not all versions of find default to the current directory. It's best to explicitly specify the directory to avoid unexpectedly failing commands later. Jun 8, 2010 at 0:47
  • 2
    Ah? Which version / platform doesn't might I ask? Not that there is anything wrong with being explicit, especially when deleting, just curious.
    – Wrikken
    Jun 8, 2010 at 0:53
  • 2
    @Wrikken: GNU find is the only one I know of that defaults to "."; BSD-derived versions tend to require the path argument. I happen to have an OSF/1 machine handy that also requires a path argument. Jun 8, 2010 at 1:02
10

Since you tagged your question with "python" here is how you could do this in that language:

target_size = 63
import os
for dirpath, dirs, files in os.walk('.'):
    for file in files: 
        path = os.path.join(dirpath, file)
        if os.stat(path).st_size == target_size:
            os.remove(path)
6

The Perl one liner is

perl -e 'unlink grep {-s == 63} glob "*"'

Although, it is always a good idea to test what it would do before running it:

perl -le 'print for grep {-s == 63} glob "*"'

If you want to walk an entire directory tree, you will need a different versions:

#find all files in the current hierarchy that are 63 bytes long.
perl -MFile::Find=find -le 'find sub {print $File::Find::name if -s == 63}, "."'

#delete all files in the current hierarchy that 63 bytes long
perl -MFile::Find=find -e 'find sub {unlink if -s == 63}, "."'

I am using need $File::Find::name in the finding version so you get the whole path, the unlinking version doesn't need it because File::Find changes directory into the each target directory and sets $_ to be the file name (which is how -s and unlink get the filename). You may also want to look up grep and glob

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.