Sort by type in linux

How to make ls sort by file extension and then name?

By default the ls command sorts just by filename, but I want directories to appear before other file types. I might even want files to be sorted by extension, like the way Windows explorer sorts by the type column. Is there a way to do something similar with ls?

7 Answers 7

I think the complete answer is more of a combination of the above.

-X (later —sort=extension ) has been supported on Linux since at least FC3 and will sort based on extension. —group-directories-first was added more recently (maybe around FC8?). However, combining the two doesn’t seem to work (at least on FC8).

The primary issue seems to be with the use of singular primary sort keys. See this mailing list discussion for some insight into it.

I know this post is rather old, but to others coming here from e.g. Google (like I did): The combination of —sort=extension and —group-directories-first (or only —group-directories ) works fine for me on Ubuntu 12.10. Worth a shot on your machine too! =)

Yes no problem combining -X / —sort=extension with —group-directories-first and anything else I’ve tried on modern Linux distros. The OP is referring to Fedora Core 8 (released 2007) so chances are any such problems are in the distant past.

I used ls -p -1v -x —group-directories-first and got the following order test21.txt test22.txt test22.webp test23.txt is there a way to combine -1v and -x options?

-X is the option you’re looking for:

On bash, this will sort of work:

 The rev utility copies the specified files to the standard output, reversing the order of characters in every line. If no files are speci- fied, the standard input is read. 

So 1. ls gives its output, with any flags you want 2. each line is reversed 3. then they’re sorted 4. and reversed again 5. like this:

  1. like this:
  2. each line is reversed
  3. then they’re sorted
  4. and reversed again So
  5. ls gives its output, with any flags you want

Or, more to the point, as below. They’re sorted by last character, then next-to-last, etc. All the .rtf files, for example, are listed together, after a .save file and another file with no extension whose name ends in ‘e’. Then come .png files, and so on. This will also work with ls -l, because the extension is normally the last thing on the line (exceptions if you have lines like «tmp@ -> /home/jones/tmp», where links are followed by their targets).

$ ls | rev|sort|rev cslu1 ls.mp2 ls.mp3 ls.mp4 trees_110214-15 PAT CSLU Proxy Form.doc finannbyid toannbyid 101209ssi.txt.save to_annotate_size Matas-time-by-week-integration2.rtf cyp3.rtf data-dir-scan.perl.doc.rtf whence-r21-numid.rtf platypus.rtf Screen shot 2011-01-21 at 2.17.50 PM.png emacs print help.png log new_month_log special Google-ngram-critique.html perl_path.html nl DWE_BEN_89808.2.ann foo d.o.foo 100811_from_iMac_Documents_in_dock.zip to-palikir.zip tmp file-cleanup bar data-scan-docs cmp-mg-ann-numids finished_numids to_annotate_numids manls.ps Mike_address_ticket cyp2.out cyp3.out locate-cyp.out manls.out DWE_BEN_89808.2.text tag2.txt l2.txt du-h-d3.txt finished_ann_numids_110407_1714.txt finished_all_numids_110407_1718.txt data-dir-scan.perl.doc.txt whence-r21-numid.txt finannid.txt toannid.txt b9-workspace-anndiff.txt tag.txt duh.txt d.o-mail.txt safextn.txt mg3longhdr.txt finished_numids.txt 41692-langnames.txt TimeAnnotationGuidelines.txt 41langs.txt thing4-homedir-links.txt bnlinks.txt grants.txt mata-file-reports.txt logx.txt logx b9-workspace-anndiff.txt~ bnlinks.txt~

Источник

Читайте также:  Canon mf3010 linux drivers

Linux sort Command with Examples

The sort command is a tool for sorting file contents and printing the result in standard output. Reordering a file’s contents numerically or alphabetically and arranging information in ascending or descending order improves readability.

In this tutorial, you will learn to use the Linux sort command and see useful examples.

Linux sort command tutorial with examples.

Linux sort Syntax

The sort command has the following syntax:

Note: While the sort command arranges data in the specified order, the grep command displays or hides the specified information. Follow our tutorial to learn to use the grep command.

Running the sort command without [options] outputs the file’s contents and applies the default sorting rules for the current locale.

  • Lines starting with a number go before the lines beginning with a letter, arranged in ascending order (1-10).
  • Lines starting with letters are sorted in ascending alphabetical order (A-Z).

For example, the following file has multiple random lines:

Using the cat command to show a file

Run sort to arrange the file’s contents in the default manner:

Sorting a file

The example above shows how the sort command arranges lines by default when no options are specified.

Note: The sort command assumes the data is in ASCII format. The locale settings affect the character’s encoding and sorting. For example, to sort uppercase letters first, set the LC_ALL environment variable to the POSIX locale ( C ). Run LC_ALL=C to set the environment variable.

Linux sort Options

Specify an option to change the sort command sorting rules. The most used options are listed in the table below:

Short option form Long option form Description
-b —ignore-leading-blanks Causes sort to ignore leading blanks.
-d —dictionary-order Causes sort to consider only blanks and alphanumeric characters.
-f —ignore-case Ignores the default case sorting rule and changes all lowercase letters to uppercase before comparison.
/ —files0-from=F Reads input from the files specified by NUL -terminated names in the specified F file. If F is , sort reads names from standard input.
-M —month-sort Sorts lines according to months (Jan-Dec).
-h —human-numeric-sort Compares human-readable numbers (e.g., 2K 1G).
-n —numeric-sort Compares data according to string numerical values.
-R —random-sort Sorts data by a random hash of keys but groups identical keys together.
/ —random-source=FILE Gets random bytes from the specified FILE .
-r —reverse Reverses the comparison results.
/ —sort=WORD Sort data according to the specified WORD : general-numeric -g , human-numeric -h , month -M , numeric -n , random -R , version -V .
-c —check, —check=diagnose-first Checks if the input is already sorted but doesn’t sort it.
/ —debug Annotates the part of the line used for sorting.
-k —key=KEYDEF Sort data using the specified KEYDEF , which gives the key location and type.
-m —merge Causes sort to merge already sorted files.
-o —output=FILE Redirects the output to FILE instead of printing it in standard output.
-t —field-separator=SEP Uses the specified SEP separator instead of non-blank to blank transition.
-z —zero-terminated Causes sort to use NUL as the line delimiter instead of the newline character.
/ —help Displays the help file with full options list and exits.
/ —version Outputs the program version and exits.
Читайте также:  Настройка nat astra linux

Linux sort Examples

Below are examples of using the sort command to arrange file contents in different ways.

Example 1: Save Output to File

The sort command only displays a file’s contents after arranging them, but it doesn’t change the file. However, the -o option allows you to save the sort command output to a file.

For example, the following command sorts the data in the default.txt file and saves the output to the sorted.txt file:

sort -o sorted.txt default.txt

Saving the sort command output in a file.

Running cat outputs the new file’s contents.

Another way to save the sort command output is to redirect the output to a file:

sort default.txt > sorted.txt

Example 2: Check for Sorting in File

Specify the -c option to check if a file’s contents have already been sorted. If the contents are already sorted, there’s no output from the sort command.

However, when sort finds an unsorted line, it outputs a message reporting the first line is out of place.

Checking if a file

The command outputs a message reporting the number and contents of the first unsorted line.

Example 3: Sort Multiple Files

There are two ways to sort multiple files:

1. List filenames as arguments separated with a space.

Sort multiple files simultaneously by specifying the respective file names as arguments, separated by whitespace. The files’ contents are joined together, sorted, and printed in standard output.

sort default1.txt default2.txt

Using sort to arrange the contents of multiple files simultaneously.

The command concatenates, sorts, and prints both files’ contents.

2. Pipe the find command output to sort .

Another way to sort multiple files simultaneously is to pipe the find command output to sort and use the —files0-from= option in the sort command.

Specify the -print0 option in find to end file name with the NUL character and ensure the program properly reads the file list.

find -name "default?.txt" -print0 | sort --files0-from=-

Piping the find command output to sort to arrange the contents of multiple files simultaneously.

The example above concatenates and sorts the default1.txt and default2.txt files.

Example 4: Sort by Fields

By default, sort compares the entire line’s contents and decides how to sort it. To compare according to a data subset, specify which fields to compare using the -k option.

The -k option takes the following syntax:

-k [ FStart [ .CStart ] ] [ Modifier ] [ , [ FEnd [ .Cend ] ][ Modifier ] ]
  • FStart . The beginning of the line.
  • CStart . The first column in the field.
  • Fend . The end of the line.
  • CEnd . The last column of the field.

The sort key includes all characters beginning with the field specified by the FStart variable and the column specified by the CStart variable. The key ends with the field specified by FEnd and the column specified by CEnd .

Not specifying Fend assumes the line’s last character as the end. Without specifying CEnd , the last character in the FEnd field is assumed.

Читайте также:  Tail linux for windows

If there is any space between the fields, sort considers them as separate fields.

For example, the lines in the following file contain three fields:

Viewing a file

Sort the data based on the second field by running:

Sorting a file

The command sorts the data according to the second field and ignores the first field.

Note: By default, sort assumes that fields are separated by whitespace. If there are multiple blank characters, sort considers them a part of the following field for sorting purposes. Specify the -b option to ignore any leading blank characters.

Example 5: Sort in Reverse Order

Use the -r option to sort the data in reverse order, i.e., in reverse alphabetical order or highest to lowest numbers.

For example, the following file is sorted with the default sorting rules:

Sorting a file

Specifying the -r option reverses the sorting order:

Reverse sorting a file

Example 6: Remove Duplicate Entries

The -u option allows sort to remove duplicate entries from a file. For example, the following file has several duplicate entries:

Viewing a file with duplicate entries with cat.

Specifying the -u option sorts the data and removes the duplicate lines:

Removing duplicate entries from a file output in sort.

Example 7: Sort by Months

Specify the -M option to arrange data according to months listed in a file.

To demonstrate sorting by months, create a file populated by the ls command output:

Redirecting the ls command output to a file.

Sort the data from the ls -l output by months by running the following command:

Sorting a file

The command sorts the file contents based on the sixth field containing the file creation month.

Example 8: Randomly Sort Data

Use the -R option to randomly arrange data without applying any sorting criteria.

For example, the following file contains several lines sorted numerically:

Viewing a file with ordered contents.

Mix up the line order with the following command:

Randomly sorting a file

The output shows that data is now randomly sorted.

Example 9: Specify a Delimiter

sort separates fields in a line using whitespace (spaces or tabs) as field delimiters. Specify the -t option to change the field delimiter to a different character.

For example, the following file contains multiple fields, including a person’s name, job title, and place of residence:

Viewing a file with multiple fields.

Sorting the file by place of residence without changing the delimiter doesn’t work because some cities have a space in the middle of their name. The space makes sort interpret the city name as two fields instead of one.

Change the delimiter to a comma ( , ) to properly sort the file’s contents:

Changing the default delimiter in the sort command.

Changing the delimiter produces the desired output.

Example 10: Sort a Stream Output

Another way to supply input to the sort command is to use the pipe ( | ) operator. Piping into sort allows it to arrange another command’s output and, optionally, save the results into a file.

The following example shows how to pipe the ls command output into sort and arrange the contents by file size:

Piping into the sort command and sorting the output based on file size.

The -nk5 options specify numeric sorting in the fifth field.

This tutorial showed how to use the sort command to rearrange a file’s contents effectively. Easily arrange large data sets in an ascending or descending order using sort .

For more Linux commands and a downloadable PDF cheat sheet, refer to our Linux commands cheat sheet.

Источник

Оцените статью
Adblock
detector