Basic CLI: Viewing File Content EffectivelyMastering File Viewing Commands in Linux

Introduction

When working with the command line in Linux, viewing and manipulating file content is a frequent task. Whether you need to display an entire file, paginate through large text files, or sort contents for better readability, the CLI offers powerful utilities.

In this guide, we'll explore essential commands such as cat, more, less, and sort, breaking down their functionalities and practical use cases.


cat – Concatenating and Viewing File Content

The cat command, short for "concatenate," is a simple yet powerful tool for viewing and merging files.

Basic Usage:

cat config.cfg

This displays the full content of config.cfg.

Numbering Lines:

cat -n config.cfg

Using -n adds line numbers to all lines, whereas:

cat -b config.cfg

Only numbers non-empty lines.

Creating a File:

cat > myFile.txt

This creates myFile.txt and allows text input (Ctrl+D to save).

Displaying Hidden Characters:

cat -A config.cfg

This reveals end-of-line markers and tab characters.


more – Viewing Large Files Page by Page

If a file is too large for a single screen, more provides a paginated view.

Basic Usage:

more fileName

This displays content one screen at a time. Press Enter to scroll and q to quit.


less – A More Advanced Pager

Unlike more, less allows bi-directional navigation and searching within a file.

Basic Usage:

less config.cfg

Navigate using arrow keys. Search using /search_term, and quit with q.

Show Line Numbers:

less -N config.cfg

Prevent Line Wrapping:

less -S config.cfg

This ensures long lines remain on one row.


sort – Organizing File Content

Sorting is essential for making data more readable.

Sorting a File:

sort file1.txt

Sorts the file alphabetically.

Reverse Sorting:

sort -r file1.txt

Displays results in reverse order.

Numeric Sorting:

sort -n file1.txt

Sorts numbers correctly (e.g., 1, 2, 10 instead of 1, 10, 2).

Removing Duplicates:

sort -u file1.txt

Eliminates duplicate lines.


Conclusion

Mastering these basic CLI commands enhances productivity when working with files. Whether quickly viewing content with cat, paging through large files with more and less, or sorting data for better organization, these tools are fundamental for any Linux user.

Experiment with different options and combinations to optimize your workflow and unlock the full potential of Linux CLI utilities.