Linux 命令行比较

LinuxLinuxBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

Introduction

Welcome to the future tech arena – a place where the brightest minds compete to showcase their mastery of cutting-edge technology. In today's event, we delve into the world of Linux, where the command line is the battleground and the audience is eager to witness the display of prowess in file comparison.

You, a brilliant technologist, are about to demonstrate the power of the comm command in front of a live audience. Your objective is to manipulate and analyse text files swiftly and accurately using this versatile command. Prepare to engage in a thrilling performance that will earn you the admiration of tech enthusiasts and novices alike!


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/VersionControlandTextEditorsGroup(["`Version Control and Text Editors`"]) linux/VersionControlandTextEditorsGroup -.-> linux/comm("`Common Line Comparison`") subgraph Lab Skills linux/comm -.-> lab-271251{{"`Linux 命令行比较`"}} end

准备你的文本文件

在这一步中,你将创建两个文本文件,这些文件将贯穿整个实验,用于演示 comm 命令。你将生成这些文件,其中包含一系列常见的 Linux 命令,并在每个文件中添加一些独特的条目。

首先,使用以下命令创建工作目录和两个文本文件:

mkdir -p ~/project/comm-lab
cd ~/project/comm-lab
echo -e "ls\ncd\npwd\nmkdir\ntouch\ncomm\nsed\nawk" | sort > commands1.txt
echo -e "ls\ncd\npwd\ncomm\ngrep\nfind\nsed" | sort > commands2.txt

现在,你已经有了两个文件,commands1.txtcommands2.txt,它们的内容相似但不完全相同。

comm 命令简介

现在你已经准备好了文件,是时候介绍 comm 命令及其基本用法了。comm 命令用于逐行比较两个已排序的文件。默认情况下,它会输出三列:仅存在于文件1中的行、仅存在于文件2中的行,以及两个文件共有的行。

运行以下命令来查看 comm 的实际效果:

cd ~/project/comm-lab
comm commands1.txt commands2.txt

这将输出显示两个文件之间的差异和相似之处。

Extracting Unique and Common Lines

In this step, we'll explore how to use comm with options to extract either the unique or common lines. The options -1, -2, and -3 will suppress the corresponding columns.

First, let's extract the lines that are unique to commands1.txt:

comm -23 commands1.txt commands2.txt > unique_to_file1.txt

Next, find the lines that are common to both files:

comm -12 commands1.txt commands2.txt > common_lines.txt

提取唯一和共有的行

在这一步中,我们将探索如何使用 comm 命令的选项来提取唯一或共有的行。选项 -1-2-3 分别用于抑制对应的列。

首先,提取仅存在于 commands1.txt 中的行:

comm -23 commands1.txt commands2.txt > unique_to_file1.txt

接下来,提取两个文件中共有的行:

comm -12 commands1.txt commands2.txt > common_lines.txt

总结

在本实验中,我们探索了如何在 Linux 命令行中使用 comm 命令快速高效地比较和分析文本文件的内容。你成功地演示了如何创建文件、运行 comm 命令以识别相似性和差异,并使用选项提取唯一和共有的行。

你在未来科技舞台上的精彩表现启发了观众,并展示了 Linux 命令行工具的实用性。这些知识是掌握 Linux 和开发高级自动化脚本的基石。

您可能感兴趣的其他 Linux 教程