Dir command: force output to one filename per line, full path included, but nothing else

command line

This will probably seem to be a simple question for advanced users, but I have tried with no success.

I want to get a file list in the terminal using the dir command, having the following format: only one file per line, full path included, but no other info, for example:


Now I have observed that I'll get this output automatcally without using switches on external drive folders and directing the output into a file. But on the harddrive it will default to the "names-only in columns" style.

How can I force dir to instead use the output format that I want?

Best Answer

This will do exactly what dir does, but it will print full paths instead of relative paths, including directories, files, symlinks and excluding hidden entries:

find . -maxdepth 1 ! -name '.*' -exec realpath -s {} +
  • find . -maxdepth 1 ! -name '.*' -exec [...] {} +: will list every directory / file / symlink in the current working directory, excluding hidden entries, recursively, limiting the recursion's depth to 1 level (i.e. to the current working directory), passing each entry in the output as an argument to [...];
  • realpath -s: will print the full path of an entry, without resolving symlinks' paths

Since this will print entries based on find's output, I'd print the output of realpath NUL-separating each entry, and I'd sort the output using LC_COLLATE=C sort -z, passing sort's output to xargs -0 printf "%s\n" (to deal with the edge case of filenames containing newlines), and since by now the command has become pretty verbose, I'd also put it in an alias for convenience:

alias my_dir="find . -maxdepth 1 ! -name '.*' -exec realpath -zs {} + | LC_COLLATE=C sort -z | xargs -0 printf '%s\n'"
% tree -a
├── dir
│   ├── file1
│   ├── file2
│   └── file3
├── file
├── file_with_\012newline
├── .hidden_file
└── symlink -> /bin

3 directories, 6 files
% alias my_dir="find . -maxdepth 1 ! -name '.*' -exec realpath -zs {} + | LC_COLLATE=C sort -z | xargs -0 printf '%s\n'"
% my_dir
Related Question