📌  相关文章
📜  linux 从一个文件中删除另一个文件中的行 - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:17:22.525000             🧑  作者: Mango

Linux 从一个文件中删除另一个文件中的行 - Shell-Bash

在Linux中,我们经常需要在文件中删除特定的行匹配模式。 但是,有时我们需要从一个文件中删除另一个文件中的行。 本文将介绍如何使用Shell-Bash删除一个文件中的另一个文件中的行。

步骤1:创建两个文件

首先,在当前工作目录中创建两个文件,一个名为file1.txt,一个名为file2.txt,并向两个文件中添加内容。 您可以使用以下命令完成此操作:

echo "This is some content in file1.txt." > file1.txt
echo "This line should be removed." >> file1.txt
echo "Another line in file1.txt." >> file1.txt

echo "This is some content in file2.txt." > file2.txt
echo "This line should also be removed." >> file2.txt
echo "Another line in file2.txt." >> file2.txt
步骤2:创建Shell脚本

接下来,我们使用Shell脚本来删除一个文件中的另一个文件中的行。 创建一个名为remove_lines.sh的新文件,并将以下内容添加到该文件中。

#!/bin/bash

# Set the input and output files
file1="file1.txt"
file2="file2.txt"
output="output.txt"

# Loop over each line in file1
while read -r line
do
  # Check if the line is in file2
  if grep -Fxq "$line" "$file2"
  then
    # Skip the line if it is in file2
    continue
  fi

  # Otherwise, add the line to the output file
  echo "$line" >> "$output"
done < "$file1"

这个脚本做了什么?

  • 它定义了文件名(file1file2)和输出文件名(output)变量。
  • 它启动一个循环来遍历file1中的每一行。
  • 对于每一行,它使用“grep”命令检查是否在file2中存在该行。
  • 如果该行存在于file2中,则跳过该行;否则,将该行添加到输出文件output中。
步骤3:运行Shell脚本

要运行脚本,请使用以下命令:

bash remove_lines.sh

该脚本会从file1.txt中删除file2.txt中的行,并将其输出到output.txt文件中。

结论

在Linux中,您可以使用Shell-Bash脚本从一个文件中删除另一个文件中的行。 通过使用Shell脚本,您可以自动执行这个任务,并将其添加到您的脚本库中以备将来使用。