Sometimes, tasks that might take hours to code can be accomplished in minutes with the terminal.
This article assumes you’re already comfortable with basic commands like rm, pwd, and cd.
-
grep
Need to find where a function or variable is used in your codebase, or sift through logs to locate specific entries? grep can help you with that.
The grep command searches for specific patterns in files. It’s like having a supercharged search function that digs into file contents.
How and when to use grep
The basic syntax for the grep command goes as the following;
Case-insensitive search: Add the -i flag to ignore case differences.
Count occurrences: Use the -c flag to count the number of matching lines.
Analyzing logs: If you’re troubleshooting an issue, you can use grep to find specific error messages in logs.
Search for Multiple Patterns: You can search for multiple patterns by using the -e flag multiple times.
Match either “error” or “404” in system.log.
Recursive Search: To search for a pattern in all files within a directory and its subdirectories, use the -r (or —recursive) flag.
This will search through all files in the specified directory and its subdirectories. The -o option tells grep to print only the matched parts of the line.
The pipe | takes the output from the command on the left (grep) and uses it as input for the command on the right (wc -l). wc -l counts and displays the number of lines in its input.
-
man
The man command stands for “manual.” It helps you find detailed information about other commands and programs.
-
cat
The cat command is short for “concatenate.” It’s used to display the contents of a file, combine files, or create new ones.
Combining Files: One of the key features of cat is its ability to combine multiple files into one. For instance, if you want to merge file1.txt and file2.txt into file3.txt, you can do this:
This command above takes the content of file1.txt and file2.txt and merges them into file3.txt. The > operator is used to direct the combined output into a new file.
Creating New Files: You can also use cat to create new files. Type your text, and when you’re done, press Ctrl+D to save and exit.
cat is helpful for viewing smaller files, but for very large files, it can be overwhelming as it dumps everything at once. In such cases, it’s better to use commands like less or head to view files in a more controlled way.
-
head
You often don’t need to see all the content when working with large files. Instead of using cat to display everything, the head command lets you preview just the first few lines of a file.
This is especially useful for checking the structure of CSV files, logs, or any other large text files.
By default, head shows the first 10 lines of a file:
If you need more or fewer lines, you can specify the exact number using the -n option:
Previewing CSV Headers: For CSV files, head is perfect for quickly checking the header or structure:
-
awk
awk is a powerful tool for pattern scanning and processing. It’s particularly useful for manipulating and analyzing text files and data streams.
With awk, you can filter, extract, and transform data in a file or from command output.
awk efficiently extracts and combines data from various sources using its associative arrays. Suppose you have two CSV files:
employees.csv
salaries.csv
Use awk to merge these files and display each employee’s name with their salary.
Rundown
- NR==FNR {salaries[$1]=$2; next}: While processing the first file (salaries.csv), store salaries in an associative array. The employee ID ($1) is the key, and the salary ($2) is the value. This runs only for the first file.
- FNR==1 {next}: Skip the header line of the second file (employees.csv).
- {print $2, salaries[$1]}: For each line in the second file (employees.csv), print the employee’s name ($2) and their salary from the array (salaries[$1]).
You can also save the results to a new file.
-
sed
sed, short for Stream Editor, is a powerful tool for text processing in the terminal. It allows you to find, replace, insert, or delete text within files or streams of data.
You can use it for quick edits without opening a text editor, making it great for scripting and automation.
Replace a word or pattern in a file: Replacing “Trevor” with “John”.
If you want save the changes, use the -i option.
Print Specific Lines: Print only specific lines from a file.
This prints lines 2 through 4.
Regular Expressions: sed supports regular expressions, allowing for complex search-and-replace operations. For example, replace all digits with “X”:
Renaming Files in Bulk: Let’s say you have multiple files with the extension .txt and you want to rename them to .md.
sed is highly versatile, and these examples just scratch the surface
-
tail
tail is the counterpart to head. It allows you to view the last few lines of a file rather than the first. It’s commonly used to monitor log files or check the end of a document. By default, tail shows the last 10 lines of a file.
Viewing More or Fewer Lines: You can adjust the number of lines shown using the -n option.
Real-Time File Monitoring: One of the most powerful features of tail is the -f option, which allows you to follow a file as it grows. This is especially useful for watching log files in real-time.
As new lines are added to 1.md, tail will automatically display them.
-
chmod
Each file has three sets of permissions: owner, group, and others. These are typically represented in a format like rwxr-xr—
- r: Read permission
- w: Write permission
- x: Execute permission
The file permissions -rw-r—r— indicate that:
- Owner (trevorindreklasn): Has read (r) and write (w) permissions.
- Group (staff): Has read (r) permissions.
- Others: Have read (r) permissions.
The @ symbol indicates that the file has extended attributes, which are additional metadata beyond standard file permissions.
File permissions control who can read, write, or execute a file, ensuring security and proper access management by preventing unauthorized users from modifying or viewing sensitive data.
To restrict access to sensitive.md so that only the root user or superadmins can view and write to it, you can use the chmod command to modify the file’s permissions.
First, ensure the file is owned by the root user or a superadmin. You might need sudo for changing ownership:
Only the owner (root) has read and write access. While the group and others have no permissions. This restricts access to the file, making it readable and writable only by the owner.
Improper file permissions can lead to security issues or system problems
-
Unauthorized Access: File containing sensitive information, like passwords or financial data, has overly permissive settings (e.g., chmod 777), anyone on the system can read or modify it. This could lead to data breaches or unauthorized access to sensitive information.
-
Malware Installation: A file or directory with write permissions for all users (e.g., chmod 777) could be exploited by attackers to place malicious scripts or software, potentially compromising the entire system.
-
Data Corruption: If files that should be read-only (e.g., logs or system configurations) are accidentally given write permissions, users or applications might inadvertently corrupt or erase critical data, leading to system instability or loss of important information.
-
xargs
The xargs command builds and runs commands using input from other commands. It’s used to pass a list of items as arguments to another command.
Suppose you have a list of files that you want to delete.
Instead of deleting them one by one, you can use xargs to pass the list of files to rm.
Creating Multiple Directories: If you have a list of directory names in a file and want to create all of them, you can use xargs with mkdir.
Compressing Files: If you have multiple files that you want to compress using gzip, you can use xargs to pass the filenames to gzip.
-
find
Search and locate files and directories within your file system based on various criteria. It’s highly customizable and can be combined with other commands for complex tasks.
The find command searches for occurrences of “astro” within the node_modules directory, returning paths to files and directories with that name, including executables and package files.
Cleanup old log files: Regularly delete log files older than a month to free up disk space.
Backup important files: Locate and copy all .docx files from home directory to a backup location.
The find command is incredibly versatile and can be tailored to suit a wide range of file management tasks.
Honorable Mentions
- jq: Slice, filter, map and transform structured data with the same ease that sed, awk, grep.
- cut: A command used to remove sections from each line of files.
- netstat: A network utility to display network connections, routing tables, and interface statistics.
- ping: A tool to test the reachability of a host on an IP network and measure round-trip time.
- ifconfig: A command to configure network interfaces (deprecated in favor of ip).
- telnet: A program to interact with remote hosts over a network using the Telnet protocol.
- sftp: An interactive file transfer program that uses the SSH protocol.
- wget: Network utility to retrieve files from the World Wide Web using HTTP and FTP.
- ps: Displays information about running processes.
- top: A task manager to view and manage running processes in real-time.
- kill: A command used to send signals to processes, typically to terminate them.
- comm: A command that compares two sorted files line by line.