4

When I am using the command to find all the files in a directory and its sub directories and redirecting the output into a file result.txt, then in result.txt file I am getting all the files including result.txt but I don't want result.txt.

like I am doing

find . -type f > allfiles.txt

in result I am getting as

./test1/test3/file4
./test1/file3
./test2/test4/file6
./test2/file5
./allfiles.txt

How to avoid that?

  • 1
    Why not just redirect to a file in a different directory? find . -type f >/tmp/allfiles? – Lee Daniel Crocker Nov 15 '17 at 17:40
  • The > file bit is handled by the shell before the program is started, so if you don't want that to happen then, you cannot pipe it to there in this way. – Thorbjørn Ravn Andersen Nov 15 '17 at 18:47
8

Simply, don't put your allfiles.txt file into the same directory you're runing find for. Put it somewhere else, like:

find . -type f > /tmp/allfiles.txt

Or if it has to be in the same directory, filter it our with grep:

find . -type f | grep -vxF ./allfiles.txt > allfiles.txt

(assuming there are no other files called ./foo\n./allfiles.txt for instance)

  • See edit with -x and -F to catch even fewer files (still potentially a problem with filenames containing newline characters as noted). – Stéphane Chazelas Nov 15 '17 at 11:52
16

Here with find specifically, you can do:

find . ! -path ./allfiles.txt -type f > allfiles.txt

More generally, you can delay the creation of the output file until after the command has returned using moreutils' sponge command:

ls -lRA | sponge allfiles.txt

Though that does mean storing the whole output in memory.

If moreutils is not installed (it's generally not by default), you can implement sponge as:

sponge() {
  perl -0777 -e '$text=<STDIN>;
                 open STDOUT, ">", shift or die$!;
                 print $text' -- "$@"
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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