How to list and sort files in Linux

How to list and sort files in Linux

  • Linux
  • 670 Views

The ls Command

The ls command is used to list files or directories in Linux and other Unix-based operating systems to the standard output. By default it displays the content of the current directory in alphabetical order by file name

1. Listing files by name

to list files by name just type the ls command

ls 

 

2. Listing files in reverse name order

to list files by reverse name just append the "r" (reverse) option

ls -r

 

3. Listing directory only

to list directories only use the "-d" option

ls -d *

 

4. Listing files along with hidden files

to list files along with hidden files use the ls -a or ls -all comand

ls -a

 

5. Listing files from another directory

to list files from another directory just append the path in front of the ls command 

ls [directory path]
ls /    (list content of root)
ls  ..   (list files in parent directory)
ls ../..  ( for contents two levels above)
ls ~   (list files in user's home directory)

 

6. Listing files by size

to list files by size append the -S option

ls -S

 

7. Listing files by age

to list files by age append the -t option for accessing files by modification date

ls -t

 

8. Display detailed information

to display detailed information about a directory append the -l  option, this uses a long listing format

ls -l

You have, from left to right: the file permissions (and if your system supports ACLs, you get an ACL flag as well) the number of links to that file the owner of the file the group of the file the file size in bytes the file modified datetime the file name

 

9. Display files in human readable file sizes

to display files in human readable information append the -h  option

ls -lh

 

10. List files with subdirectories

to display content of a directory and its subdirectories use the ls * command

ls *

 

11. Display files recursevely

Type the ls -R command to list all files and directories with their corresponding subdirectories down to the last file:

ls -R

 

12. List files and output the result to a file

Type the ls > [file name ] command to print the output of the preceding command into a file. You can use any of the flags discussed before like -la .

The result will be outputted into a file and not logged to the command line.

ls -alh > homefiles.txt

 

Conclusion

There are tons of other commands and combinations you can explore.

you can run ls --help or man ls which will display a manual with all possible options for the ls command: