Forrest logo
back to the cat tool

file_manipulation:warp:4ff5b

Sort a file by line length
$ cat ${file_name} | awk '{ print length, $0 }' | sort -n -s | cut -d" " -f2-
try on your machine

This command performs the following steps:

  1. cat ${file_name}: cat is a command used to display the contents of a file. ${file_name} is a placeholder that represents the name of the file you want to display. So, this part of the command reads the contents of the specified file and outputs them.

  2. | awk '{ print length, $0 }': The output from the previous step is piped | to the awk command. awk is a versatile text processing tool. In this command, it is used to print the length of each line along with the line itself. Here, length will print the length, and $0 represents the entire line.

  3. | sort -n -s: The output from awk is again piped | to the sort command. sort is used to sort the input lines. Here, -n option is used to sort numerically, and -s to maintain the original order when the values to be sorted are the same. So, this step sorts the input lines based on their length.

  4. | cut -d" " -f2-: Finally, the output from sort is piped | to the cut command. cut is used to extract specific columns or fields from lines of input. Here, -d" " specifies that the delimiter is a space, and -f2- means to print fields starting from the second field to the end. So, this step extracts and outputs the original lines, removing the length that was printed by awk.

In summary, this command reads the contents of a file, prints the length and the line itself using awk, sorts the lines based on their length using sort, and then extracts and outputs the original lines without the length using cut.

This explanation was created by an AI. In most cases those are correct. But please always be careful and never run a command you are not sure if it is safe.
back to the cat tool