Viewing File Content
To inspect a small file quickly, use thecat command with the filename. For example:
tac command is available:
tail command displays the last 10 lines by default, which is useful for checking the most recent log entries. Conversely, the head command shows the beginning of a file.
For instance, consider a log file with 10 lines (keep in mind that empty lines might also count):
-n option with both tail and head.
Automating Text Replacement with SED
Editing multiple instances manually in large files can be error-prone and time-consuming. The Stream Editor (SED) automates search and replace tasks efficiently. For example, if a file listing user details has the country “Canada” misspelled as “canda”, you can preview the correction with:s/canda/canada/g: The substitute command wherecandais replaced withcanadaglobally on each line.- Single quotes ensure Bash does not interpret special characters.
- The
-gflag replaces all occurrences in each line.
Always back up your files before performing in-place edits with
sed -i.Extracting Data with Cut
Thecut command is ideal for extracting specific columns from a file. For example, to extract the first column—which often contains names—from a space-separated file, use:
-d ' ' sets the delimiter to a space, while -f 1 specifies that the first field should be extracted.
If the file is comma-separated, simply adjust the delimiter. For instance, to extract the third field (which could represent country names) and save the output to countries.txt, run:
>) saves the extracted output to a new file.
Removing Duplicate Entries
After extracting data—like a list of countries—you might encounter duplicate entries. Theuniq command removes duplicates from adjacent lines. For example:
uniq:
|) is a powerful technique that allows you to pass the output from one command directly into another for further processing.
Comparing Files with Diff
When system upgrades or configuration changes modify files, comparing the old and new versions is crucial. Thediff command highlights these differences. Consider the following example:
1c1 indicates that line 1 of file1 differs from line 1 of file2. The < symbol shows content from file1, while > represents content from file2.
For more context, use the -c option:
-y option:
sdiff for a similar side-by-side comparison:
Using the
diff command with different options (-c, -y, or sdiff) can help you pinpoint changes more easily during system upgrades or when troubleshooting configuration issues.Summary
This guide introduced a variety of Linux commands—cat, tac, head, sed, cut, sort, uniq, and diff—that are invaluable for viewing, editing, and comparing file content. Mastery of these tools not only streamlines your workflow but also enhances your ability to manage and debug files in any Linux environment.
For more detailed explanations and advanced use cases, consider exploring additional Linux command-line resources.