How do I list (ls) the content of a folder/directory recursively but to a depth of only one folder/directory?
I have the following folder structure:
folderA:
folderB1:
folderC1:
fileD1:
fileD2:
fileC2
fileC3
folderB2:
folderC4:
fileD3:
fileD4:
fileC5
fileC6
I am in the parent folder of folderA
and would like to list everything in it and its subfolders but not subsubfolders. So I would like to see:
folderB1/folderC1
folderB1/fileC2
folderB1/fileC3
folderB2/folderC2
folderB2/fileC4
folderB2/fileC5
Is that possible? At the moment, I use ls -R folderA
which takes me down a rabbit hole of hundreds of subsub..subfolders I am not interested in. I would like to stop at a certain depth. Ideally, there would be an option like depth 1
to list the content of folderA and its subfolders and stop.
I am working on macOS X High Sierra.
You don't want a recursive listing, then, because as you've seen, recursive means "to the end", not "to some arbitrary stopping point".
To list two levels beneath folderA while in folderA's parent,
(cd folderA && ls -d -- */*)
The crux of it is the */*
wildcard/glob; that asks the shell to generate all of the immediate subdirectories (with */
) and then all of its entries (the final *
).
Importantly, we have to tell ls
to not expand any of those final entries if they happen to be directories; we do this with the -d
flag.
The last piece, to get the output format you're looking for, I solved by starting a subshell where we cd
into folderA in order to do the listing. Once ls
exits, the subshell exits, and we return to our current prompt & directory (above folderA).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments