Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

ls syntax to show filename and directory

Writer Sebastian Wright

I wish to use the ls command so the result looks like this:

folder1/file1.doc
folder1/file2.doc
folder1/file44.doc
folder3/file1.doc
folder66/file4.doc
folder999/file.doc

In other words I want to output the directory name as well as the filename for each row.

cd myfolder
ls * > output.txt

I think I need to add some commands to the ls line above.

Is this possible to do using ls?

3 Answers

It's much easier using find:

find folder* -type f > output.txt

The wildcard will expand to all folder names and it'll recursively list the files with their path prefixed by the folder name.

As discussed recently in Get all file paths from a certain point … (on AU), you can do this as follows:

shopt -s globstar
ls -d1 **

Note that the ls options are lower-case D and the number one.  Note that ls isn’t really doing anything here except listing its arguments; you might as well say

printf "%s\n" **

These are not limited to a certain number of levels.

If you want to include names that begin with a dot (.), you must also shopt -s dotglob.

If you only have one level (that is, all of your current subdirectories have no subdirectories in them), then

ls -1 */*

should do what you want. Note that the option is the number one, not the letter ell.

If you do have subdirectories but you don't need file listings of those subdirectories, then

ls -1d */*

should do what you want. Again, the options are one dee, not ell dee.

If your file layout is too complex, then you will need a find statement such as

find . -print | sed s:./::
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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