List only the directories October 19, 2005
Posted by Carthik in commands, snippets, ubuntu.trackback
I had a trivial problem today where I had a huge list of files in a directory, and other directories within the directory. I was looking for a specific directory and wanted to get the files out of the way. I wanted a listing of the directories within the current directory and nothing more. Luckily, with a little experimentation I was able to figure out how to do this :
$ ls -l | grep “^d”
Neat.
Another one I find myself using a lot is: ls -ltr
That’s for directories such as /var/log that have lots of files in them and you want to know which ones have been updated most recently. It lists files, in detail, in reverse order of modification time. So once all the files have streamed through your screen, the ones at the bottom are the ones that have just been updated.
find . -type d -maxdepth 1 -mindepth 1
Not to mention the wonderful program tree.
tree -d -L 1
I have written small scripts to handle this since it frequently comes up for me too. Then last month somebody showed me this:
ls -d */
I second the vote for:
ls -d */
I just learned of it myself, also about a month ago. I think it was buried in a Slashdot comment.
does anyone know _how_ `ls -d */` works? after looking at the output of `ls -d` and `ls */` i’m totally confused.
tyler, the -d says “do not descend into sub-directories, it is the same as saying -d1.
The */ says list only items ending in / (which are directories).
If you want to see hidden directories, you could do a ls -d .*/
hmm…. While this seems to work – it is NOT as documented in Ubuntu info and man pages.
Both of those reference document the -d option as:
-d, –directory
list directory entries instead of contents, and do not
dereference symbolic links
Based on that definition ‘ls -d’ should have produced the desired results – but as we know it does not.
One should note that the wildcards are expanded by bash (or the shell you are using) not by ls.
ls -d will not list directories but the entries, by default no argument leads to the current directory entry that is “.”.
All other stuff like “ls -d */” is actually shell based and expands to something like “ls -d bla/ blub/ …./” and then just prints out those single entries.
Clearly “ls */” will then list the contents of all patterns matching it and thus the files in the directories matching this pattern (read: not the hidden dirs).
As proposed some time ago the “find” command will probably lead to the “best” results as its independent of bash globbing….
That’s fine, but i need a neat list of directory names, without prefixes or trailing slashes.
How to filter this out?
Try:
# for i in $(ls -d */); do echo ${i%%/}; done
[…] There are some other ways discussed here at the Ubuntu log. […]
tree -fid is also nice. Useful in scripts.
Realizzare PCB è facilissimo con PCBFacile.
#10, i used this to have just directory names:
find . -type d -printf ‘%P\b’
find lets you format your output however you want.
This is one is good,
ls -d */ | xargs -l basename
In a tester i got that the basename is missing an operant…
i always do this ls -d */
then alias it using
lsd = `ls -d */`
so you just have to type “lsd”
well since the */ is interpreted by the shell anyhow why not use
echo */
to list directories and if you dont like the trailing “/”
echo */ ” ” | sed “s/\/ /\n/g”
?
this is neat vsutra, nice, how about folders whose names consists of a space and we would need to move them?
thanks in advance and regards
why the h311 isn’t there an option right in ls to do this? why do I have to pi55 around with for loops and crap like that to get a basic piece of information. List me the damn directories ONLY.
too much to ask?
To lejeczek:
Well since the default field separator includes space, we’ll need to change the code slightly to this:
IFS=$’\x0A’;for i in $(ls -1d */); do echo ${i%%/}; done
It should display out directories with spaces in it properly.
I’m not entirely sure whether I understand the second part of your question, but maybe this will help in manipulating the output:
IFS=$’\x0A’;for i in $(ls -1d */); do echo “\”${i%%/}\””; done
To weenie:
ls -d */
thats all you need to do just to list down the directories, the rest of it is just to format the output.
find . -maxdepth 1 -mindepth 1 -type d -print0 | xargs -0 | sed ‘s/.\//\n/g’
This will get the directories only even if the has spaces or other characters in the name and then strip out the leading ./ and replace it with a newline. drop the last | and stuff after it and add your favoritecommand to process the directories with:
find . -maxdepth 1 -mindepth 1 -type d -print0 | xargs -0 du -sh
show how much disk space each directory takes up.
this is fun
echo */*/*/
i need help.
i’m trying to backup multiple directories using tar. however i want those directories to keep their corresponding names.
e.g.
test1 = test1.tar
test2 = test2.tar
test3 = test3.tar and so on.
i tried to using the find command, to print the names, but after that i don’t know how to pipe it properly to tar.
please help
Hello,
I am using ls -d */ to get directories, but the list coming out contains not only directories but also files, behind which the commando simply puts /. The strange thing is, on my home directory it works fine, it only happens when I use it on another server (which need to be done cause my data is there).
Somebody has a suggestion?
Solved it, indirectly: the directories had short names, files longer. so i used the command ls -d /*/???/ /*/????/ /*/?????/
very strange tho
[…] What follows are a couple of ways of doing what I was trying to do, which I found in a post (and its comments) on the Ubuntu Blog, “List only the directories“: […]
ls -d */ | xargs -l basename
This wokrs good.
BUT, if a directory has a space in the name , then it is not displaying full name.
kunle – April 9, 2007
this is fun
echo */*/*/
this is alot more fun:
echo /*/*/*/
hey there!
what about ths one:
ls -R | grep ./
GREAT list! Even with the numerous variations listed here, I was unable to find one to match my exact needs – I am sure there is probably an easier way to do this, as I am a bit of a noob, but I needed a recursive list of directories within a directory, with the spaces escaped. I ended up writing this:
find . -type d | sed ‘s/ /\\ /g’
The odd thing is, when I run it within my script to assign the output to a variable, the spaces are no longer escaped, and the X’s are missing? Oh well, back to do further research…
ls -l | grep ^d | awk ‘{print $9}’ | grep -v ^\\.
[…] List only the directories « Ubuntu Blog listing of the directories within the current directory (tags: linux howto bash directories codesnips) Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages. […]
Print directory names one line at a time, without any other characters:
find . -maxdepth 1 -mindepth 1 -type d -printf %P\\n
Look ma, no pipes 🙂
Print directory names one line at a time, without any other characters:
find . -maxdepth 1 -mindepth 1 -type d -printf %P\\n
Look ma, no pipes 🙂
Nice for recursive directories permissions switching (in my case 700 -> 755):
find . -type d -mindepth 1 2>/dev/null | sed ‘s/^/”/g; s/$/”/g’ | xargs chmod 755
Thanks for ls -d */
works fine !!
nice tips indeed, it works fine for me
I was using find . -type d but ls -d */ looks better
find . -maxdepth 1 -mindepth 1 -type d | grep -v ‘^\./\.’
aliased as ldir
works for me!
sample price auto insurance new driver nyc…
Aviv preposterous anchovy …
florida insurance flood zones…
chuckles masted impostors,nullifies badness!contraband:…
I’ve really been enjoying reading all that stuff of incredible ingenuity 🙂
Thanx folks for sharing 🙂
If you wish to display files only, try this:
ls -p | grep -v ‘/$’
Oooooookay, came across this thread when trying to chmod a directory (with files) I copied from a Windoze machine (dirs=755, files=644).
If anybody wants to do just that, try this:
find . -type d -print0 | xargs -0i chmod 755 {}
find . -type f -print0 | xargs -0i chmod 644 {}
Using -print0 and -0i (be careful, these are zeros), every file’s oder folder’s name may even contain special characters like quotes. Nice.
ls -l | grep “^d” | sed ‘s/[ ][ ]*/ /g’ | cut -d ” ” -f 8
🙂
dont know if its valid but…
type cd and then press TAB key twice
And the opposite one
http://unstableme.blogspot.com/2008/12/list-only-file-and-not-directory-ls.html
ls -d */ is just what I need but ideally ls should have options like:
–dirs-only
–files-only
(maybe more for blocks and pipes?)
and an alias like lsdir (cf. lsusb, lspci)
lslatest for ls -latr (which I use a helluvalot)
There’s always bash aliases for those I guess.
Tada! Lists only top directories,in dictionary order,then pipes it into a text file:
find . -maxdepth 1 -mindepth 1 -type d -printf %P\\n | sort -d > filelist.txt
ls -1l | grep ‘^d’ | awk ‘{print $8}’
for dos/cmd NT shell [lol] use:
dir /ad /b
produces what everyone is looking for with ls
it should be an option for ls for sure, but
put this in a shell script and you can filter out directories that start with a certain character sequence, reverse the reg ex and you could make it inclusive.
find . -maxdepth 1 -mindepth 1 -type d -printf “%P\\n” | sort -d | grep -P “^[^$1]”
cool stuff amazing how many different ways there are to do something in the shell. have to love it.
@ayoy
doesn’t chmod -R do that…?
What about:
echo */
?
for listing with subdirectories
find ./ -type d
You want to allow for experimentation. ,
Removing hidden files from @Colin command,
find . -maxdepth 1 -mindepth 1 -name ‘[!.]*’ -type d -printf %P\\n
Strikes me that the originator(s) of ls should just have put in an option to filter (include/exclude) by file mode. Then you could have shown directories only, or whatever you required. It’s a strange omission.
Seems obvious really, and the annoying thing is that DOS/cmd does (sort of) have that option: dir /A
I just tried ls -ld */ and I got the exact desire output!
me too
Not to mention the wonderful program tree.
That’s for directories such as /var/log that have lots of files in them and you want to know which ones have been updated most recently. It lists files, in detail, in reverse order of modification time. So once all the files have streamed through your screen, the ones at the bottom are the ones that have just been updated.
Thanks friends information
Under Mac OS X (and likely BSD),
basename -a */
gives the desired output.
evden eve
Was a beautiful page. Thanks to the designers and managers.
anyone knows how to list directories only including hidden directories along with their details?
i know half of the solution:
ls -l -d */ # but hidden directories are not shown
See message No. 7
Hi
ls -l -d */ -explain this cmd mechanism
just another one which removes the / in the end:
ls -1d */ | awk ‘BEGIN {FS=”/”};{print $1}’
[…] Note that this relies on your shell interpreter (i.e. bash) to expand the wildcard. If this does not fit your needs, you can find many alternatives here. […]
http://destinationindia.us
destination india
VITS is a dedicated wholsale tour operator. By focusing on our core business in travel industry and refining our services through an incredibly advanced and capable reservations system, we believe we offer the most personable, efficient and profitable solution for our customers. Our travel services include India hotel booking, India tour & travel arrangements, and flight tickets booking for customers. We also assist in arrangements for the visa & passport for the travelers traveling to India.
Rajasthan Tour,GoldenTriangle Tour,Kerala Tour,Taj Mahal Tour.
I need a command which will list out all the directoies under a directory except the latest one.
and also to move the list to a different path
I say somebody should come up with the rube goldberg of this that a) has the most steps, and b) take the longest time.
On OS X I modified to:
find ./ -type f -exec sed -i “” ‘s/string1/string2/’ {} \;
after reading this thread:
http://hintsforums.macworld.com/showthread.php?t=95246
[…] Note that this relies on your shell interpreter (i.e. bash) to expand the wildcard. If this does not fit your needs, you can find many alternatives here. […]
simple
ls |grep /
antalya ev ilaçlama
[…] Note that this relies on your shell interpreter (i.e. bash) to expand the wildcard. If this does not fit your needs, you can find many alternatives here. […]
Thanks I was looking for unix command to list the directories.
how about pressing
cd
then tab twice
lol
ls -l | grep ‘^d’
Excellent:
1. ls -d */
ls -d .*/
2. find path -type d -maxdepth 1 -mindepth 1
3. ls -l | grep “^d”
Maybe like this:
ls -d */ |cut -d/ -f1
Cool. But what actually does the ‘ls -d’ part? ‘echo */’ works exactly the same. But it has problems with spaces. When I do ‘for i in `echo /*’; do echo $i; done’ I get directory with spaces split over two lines. For what reason so ever ‘for i in `echo “*/”`; echo $i; done’ works but I have no clue why, since ‘echo “*/”‘ yields just ‘*/’ as expected. Any clue?
We offer Agra tour by car, one day Agra tour, Agra tour packages, Agra tour, Agra tour from Delhi, same day Agra tour, private Agra tour, group tour packages, one day tour Agra, Agra tours, India Agra tour, Jaipur Agra tour, Delhi Agra Jaipur tour, day trip to Agra, holiday in Agra, honeymoon packages Agra, car rental services, Agra tour by Car.
ls -l –time-style=long-iso | egrep ‘^d’ | awk ‘{print $8}’
From: http://moinne.com/blog/ronald/bash/list-directory-names-in-bash-shell
find [!.]* -maxdepth 0 -type d
Excludes . and .. and outputs only directories atthe current level with no trailing slashes.
ls -R | grep : > folder.list
while read F
do
# To remove “./” from the front
tmp=${F#”./”}
# To remove “:” from the back
tmp=${tmp%”:”}
echo “$tmp”
done < folder.list
Need help with simplifying the code and remove . from the outputs, can i do it without output it to the folder.list
any ideas?
“[89]Many multilateral forums utilizing global principles, such as NATO
and OAS, ASEAN and OAU have adopted resolution to tighten border security and drug trafficking.
The idea is evergreen, and all we did to make it work
was figure out how to take the experience of a guy
who helps his clients juggle millions of dollars in investments and boil it down
to something that would be applicable to Joe Six-Pack.
Douglas Farah and Peter Finn from the Washington Post call this new wave of terrorism
“Terrorism Inc.
Pretty! This has been a really wonderful article.
Many thanks for supplying these details.
If you follow these three ways How to Make Money Blogging In 2014.
The amount of quick cash loan can alter between $50 to $ 1,000 relying
on the banks and the state in which you apply for
it. Make use also of the power of social sites such as Facebook and Twitter.
After the first wire transfer, I called the dispute department and asked who picked
up the cash if they keep records, etc. An import agent acts as a go between,
introducing foreign sellers and home based buyers to each other.
Great article and straight to the point. I am not sure if this is
truly the best place to ask but do you people have any thoughts on where
to hire some professional writers? Thx 🙂
The song they dropped onn TI’s album was Swagga like
uѕ. It tοok ɑn hour-ɑnd-ɑ-half tο reach tօ 90,000 feet befοre
bursting. t Belieνе thе Truth, Coldplay X&Y, Whiite Stripes Ԍet Bеhind Mе Satan, Editors The Back Room,
Kanye West Late Registration, Pussycat Dolls PCD, Sigbor Ros Takk.
hello there and thank you for your info – I have certainly picked up anything new from right here.
I did however expertise several technical points using this site,
since I experienced to reload the website a lot of times previous to I could get it to load properly.
I had been wondering if your web host is OK?
Not that I am complaining, but sluggish loading instances times will very frequently affect your
placement in google and can damage your high quality score if ads and marketing with Adwords.
Anyway I am adding this RSS to my email and can look out for much more of your respective interesting content.
Make sure you update this again very soon.
Hi there excellent website! Does running a blog similar to this
take a large amount of work? I’ve no knowledge of programming however
I was hoping to start my own blog soon. Anyhow, if you have
any suggestions or tips for new blog owners please share.
I know this is off subject nevertheless I just needed to ask.
Thanks!