Print list of files in a directory to a text file (but not the text file itself) from terminal

jackscorrow picture jackscorrow · Apr 30, 2017 · Viewed 19.2k times · Source

I would like to print all the filenames of every file in a directory to a .txt file.

Let's assume that I had a directory with 3 files:

file1.txt
file2.txt
file3.txt

and I tried using ls > output.txt.

The thing is that when I open output.txt I find this list:

file1.txt
file2.txt
file3.txt
output.txt

Is there a way to avoid printing the name of the file where I'm redirecting the output? Or better is there a command able to print all the filenames of files in a directory except one?

Answer

mklement0 picture mklement0 · Apr 30, 2017
printf '%s\n' * > output.txt

Note that this assumes that there's no preexisting output.txt file - if so, delete it first.

  • printf '%s\n' * uses globbing (filename expansion) to robustly print the names of all files and subdirectories located in the current directory, line by line.

  • Globbing happens before output.txt is created via output redirection > output.txt (which still happens before the command is executed, which explains your problem), so its name is not included in the output.

  • Globbing also avoids the use of ls, whose use in scripting is generally discouraged.