Practical Examples of Using comm
Now that you understand the basic usage of the comm
command, let's explore some practical examples that demonstrate its utility in real-world scenarios.
Example 1: Finding New Entries
Imagine you have two lists of users - one from last week and one from today. You want to identify which users are new (added since last week).
Let's create these files:
cd ~/project/comm-lab
echo -e "user1\nuser2\nuser3\nuser4\nuser5" | sort > users_last_week.txt
echo -e "user1\nuser3\nuser5\nuser6\nuser7\nuser8" | sort > users_today.txt
To find the new users (in users_today.txt
but not in users_last_week.txt
):
comm -13 users_last_week.txt users_today.txt
Output:
user6
user7
user8
Example 2: Finding Removed Entries
Using the same files, let's find which users have been removed since last week:
comm -23 users_last_week.txt users_today.txt
Output:
user2
user4
Example 3: Combining comm with Other Commands
The comm
command can be combined with other commands for more complex operations. For example, if we want to count how many common commands there are in our original files:
comm -12 commands1.txt commands2.txt | wc -l
This pipes the common lines to the wc -l
command, which counts the number of lines.
Output:
5
This indicates there are 5 commands common to both files.
Example 4: Using comm with Unsorted Files
The comm
command requires sorted input files. If you try to use it with unsorted files, you might get incorrect results. Let's demonstrate this:
echo -e "cat\nls\npwd\ncd" > unsorted1.txt
echo -e "ls\ncat\ngrep\npwd" > unsorted2.txt
If we try to use comm
directly:
comm unsorted1.txt unsorted2.txt
The output might be misleading because the files aren't sorted. The correct approach is to sort the files first:
comm <(sort unsorted1.txt) <(sort unsorted2.txt)
This uses process substitution to sort the files on the fly before comparing them. You should see a properly formatted result with the correct columns.
These examples demonstrate the versatility of the comm
command for comparing text files in various scenarios such as tracking changes, finding differences, and filtering data.