Thursday, March 3, 2016

How to list the directories alone


(1)  List directories Using ls command


      There is no direct switch / option to list the directories alone in the ls command .

      Command    =>  ls -d */     - This command is little tricky one . Refer the below explanation to understand this command   

             

      Usage          =>  -d option  to list the directory names but -d option need an argument. -d just eliminates displaying content of the directory ( ls * will display file and directories contents )  & display the directory name alone. argument here is */.    "*"  indicates the meta character which display all contents ( file, directory , link etc ) .  Forward slash (/) indicates the end of the directory .  Unix internally represents / is for directory in the end of the directory name. so */ means  any directory.  In Summary, when */ passed as argument to -d option, it picks the directories list and ignore the content of directories and display only the directory names


(2)  List the directories using echo command


 Command :  echo */  




 Usage:     Just echo *  will display all content of a directory .  */ display only directory . * indicates 0 or more characters & forward slash ( / ) indicates directory

(3) List directories using ls and grep commands


Command : ls -l | grep "^d"





Usage:      ls -l lists the directories and files. the permission field's ( 1st filed) 1st char denotes the file (f) / directory (d).  the grep command uses the regular expression carrot ( ^) which read the 1st character and then "d" denote first directory.  so ^d indicates search the first character which has 'd' and get its list.  If you want to display the files alone instead of directory, ls -l | grep "^-"

 (4) List directories using ls -F


Command: ls -F | grep "/$"





Usage:     -F option will differentiate adding forward slash (/) at the end of the directory name. grep command searches last character as "/" and list only those lines which are directories names

No comments:

Post a Comment