We can use the wc, sort command provided by Linux to count the number of words, the number of bytes, and the sort of letters and numbers.

We continue to use the file file.txt test data we used in Entry Level post:

img

The contents of the file.txt file

Word Counter

The wc command by default outputs the number of newlines, words, and bytes of the file:

1
wc file.txt
img

Outputs the length of the newlines, words and bytes of the file.txt file

Byte Counts

We can add the -c or –bytes parameter to output the file’s byte counts:

1
2
wc -c file.txt
wc --bytes file.txt
img

Outputs the byte counts of file.txt file

Character Counts

We can add the -m or –chars parameter to output the file’s character counts:

1
2
wc -m file.txt
wc --chars file.txt
img

Outputs the char counts of file.txt file

Word Counts

We can add the -w or –words parameter to output the file’s word counts:

1
2
wc -w file.txt
wc --words file.txt
img

Outputs the word counts of file.txt file

Newline Counts

We can add the -l or –lines parameter to output the file’s line counts:

1
2
wc -l file.txt
wc --lines file.txt
img

Outputs the line counts of file.txt file

Sorted Result

Sort One File Contents in Ascending Order

We can use the sort command to sort the letters of the file contents:

1
sort file.txt
img

Outputs the sorted contents of the file.txt file

Sort Multiple File Contents in Ascending Order

We can sort multiple files at the same time:

1
sort file1 file2 file.txt
img

Outputs the sorted contents of the file.txt file

Sort Contents in Descending Order

We can add the -r or –reverse parameter to sort the contents of the file in descending order:

1
2
sort -r file.txt
sort --reverse file.txt
img

Outputs the reversed sorted contents of the file.txt file

Sort Numeric Contents in Ascending Order

Before we start, we need to prepare a file with numeric contents:

1
2
3
4
5
6
7
8
9
echo 123 >> num_file
echo 1234 >> num_file
echo 12 >> num_file
echo 1 >> num_file
echo 21 >> num_file
echo 4321 >> num_file
echo 4231 >> num_file
echo 3241 >> num_file
cat num_file
img

Save a few lines of integer numbers to the num_file file

We can add the -n, –numeric-sort or –sort=numeric parameter to sort the integer number of the file contents in ascending order.

1
2
3
sort -n num_file
sort --numeric-sort num_file
sort --sort=numeric num_file
img

Output numeric contents in ascending order

Sort Numeric Contents in Descending Order

We can add the -n, –numeric-sort or –sort=numeric with a -r or –reverse parameter to sort the integer number of the file contents in ascending order.

1
2
3
sort -n -r num_file
sort --numeric-sort --reverse num_file
sort --sort=numeric --reverse num_file
img

Output numeric contents in descending order

References 6.1 wc: Print newline, word, and byte counts, 7.1 sort: Sort text files

Buy me a coffeeBuy me a coffee