This chapter introduces various commands used to read the contents of files without opening a full editor, and how to make quick edits directly in the terminal.
1. Quick File Viewing (cat, less, head, tail)
The Linux command line offers several utilities to quickly display file contents.
A. Displaying Entire File (cat)
The cat (concatenate) command reads data from files and outputs their contents to the standard output (your terminal screen). It is best used for short files.
To display the entire contents of a file:
cat config.txt
B. Paging Through Files (less)
For long files, using cat will cause the text to scroll past too quickly. The less command opens the file and allows you to scroll through it page by page.
To view a file interactively:
less long_log_file.log
Tip: While in
less, use the Spacebar to move down one page andqto quit.
C. Viewing Start and End (head and tail)
These commands are useful for inspecting logs or configuration files to quickly see the beginning or end.
head: Displays the first 10 lines of a file by default.tail: Displays the last 10 lines of a file by default.
To view the last 20 lines of a log file, use the -n option:
tail -n 20 error.log
2. Finding Text Within Files (grep)
The grep command (Global Regular Expression Print) is an extremely powerful utility used to search for specific text patterns within one or more files.
To search for the word “fatal” within all lines of server.log:
grep fatal server.log
Common grep Options
-i: Ignores case when searching.-r: Searches recursively through all files in subdirectories.-v: Inverts the match; displays lines that do not match the pattern.
To search for the phrase “warning” (case-insensitive) in all files in the current directory and subdirectories:
grep -ri warning .
3. Basic Command-Line Editing (Nano)
For quick changes directly in the terminal, the nano editor is simple and easy for beginners.
To open config.txt in the Nano editor:
nano config.txt
Tip: Nano displays its commands at the bottom of the screen (e.g.,
^Xmeans press Ctrl + X to Exit, and^Omeans Ctrl + O to Write Out/Save).
