In Linux, sorting a file is a chief requirement for organizing data. This tutorial will teach you to sort a text file with different options of -n, -r, -f, and -k.

Linux Sort text file options
Photo by Ali Ramazan u00c7iftu00e7i on Pexels.com

01. Sort text files using the -n option

To sort a text file using the -n option in a Linux script, you can use the sort command. The -n option tells sort to perform a numerical sort. Here's an example of how you might use it in a script:

#!/bin/bash

input_file="input.txt"
output_file="sorted_output.txt"

sort -n "$input_file" > "$output_file"

echo "File sorted numerically and saved to $output_file."

02. Sort files using the -r option

To sort a text file in reverse order using the -r option in a Linux script, you can use the sort command. Here's an example script that demonstrates how to do this:

#!/bin/bash
if [ $# -ne 1 ]; then
    echo "Usage: $0 <input_file>"
    exit 1
fi

input_file="$1"
if [ ! -f "$input_file" ]; then
    echo "Input file not found: $input_file"
    exit 1
fi

sorted_file="${input_file%.txt}_sorted.txt"
sort -r "$input_file" > "$sorted_file"

echo "File sorted in reverse order and saved as $sorted_file"

03. Sort files using the -f option

The -f option in Linux commands usually stands for "ignore case" when performing operations that involve sorting or comparing text. If you want to sort the lines of a text file using the -f option to ignore case, you can use the sort command. Here's how you can do it:

sort -f input.txt > output.txt

04. Sort files using the -k option

In Linux, you can use the sort command to sort the lines of a text file using different criteria. The -k option allows you to specify fields within each line to be used as the sorting key.

The syntax of the sort command with the -k option is as follows:

# sort -k <start_field>[,<end_field>] [options] <input_file>

For example, if you have a text file named data.txt with tab-separated values, and you want to sort it based on the second field, you would use the following command:

sort -k 2 data.txt


If you want to sort based on a range of fields, for example, from the second to the fourth field, you would use:

sort -k 2,4 data.txt

Related