How to Extract Duplicate Lines from Two Files using Grep

Abstract: Extract duplicate lines from two files using grep to identify exact matches efficiently without loading both files into memory.

Created: 2026-09-01 by
To extract duplicate lines from two files using Grep, use the -f option to treat one file as a pattern list and match it against the second file. The command grep -F -f file1.txt file2.txt outputs every line in file2.txt that exactly matches any line in file1.txt. This approach is efficient for large datasets because it avoids loading both files into memory simultaneously and leverages optimized string matching algorithms within the Grep utility itself.

Understanding the Basic Command Structure

The core of this operation relies on the -f flag, which tells Grep to read patterns from a file rather than receiving them as a command-line argument. When combined with the -F flag, Grep interprets these patterns as fixed strings rather than regular expressions. This distinction is critical because it prevents special characters like dots or asterisks in your data from being interpreted as regex metacharacters, ensuring exact line-to-line comparisons. Consider a scenario where you have source.txt containing a list of user IDs and target.txt containing a log of transactions. You want to identify which transactions correspond to users in your source list. The command structure looks like this:
grep -F -f source.txt target.txt
This command scans target.txt line by line. If a line in target.txt matches any line in source.txt, it is printed to the standard output. It is important to note that if source.txt contains duplicates, Grep will still process them, but the output will only reflect matches found in target.txt. This method is generally faster than using loops or more complex text processing tools for simple inclusion checks. For related techniques on handling duplicates, you might also explore how to compare two files and keep duplicate lines in output file, which offers variations on managing repeated entries during comparison.

Handling Case Sensitivity and Whitespace

By default, Grep is case-sensitive. A line reading "Admin" will not match "admin". If your data requires case-insensitive comparison, add the -i flag to your command. This is particularly useful when dealing with user-generated content or logs that may have inconsistent capitalization.
grep -F -i -f source.txt target.txt
Whitespace can also cause unexpected mismatches. Trailing spaces in source.txt might prevent a match even if the visible text is identical. To ensure robust matching, you should clean your input files first. Using sed to remove trailing whitespace before running Grep can save significant debugging time. For example:
sed 's/[[:space:]]*$//' source.txt > clean_source.txt
grep -F -f clean_source.txt target.txt
If you are looking for specific file names rather than content lines, understanding how to find file names with grep command can help you locate the source files themselves before performing the content comparison.

Sorting and Saving Results

The output of Grep is unsorted by default, appearing in the order they were found in target.txt. In many workflows, having a sorted result set is essential for further processing or readability. You can pipe the Grep output directly into the sort command.
grep -F -f source.txt target.txt | sort > results.txt
This pipeline creates a new file named results.txt containing all matching lines, sorted alphabetically. If you need to remove duplicate lines from the final output (in case target.txt had multiple identical entries), you can append the -u flag to sort: sort -u. This ensures each unique matching line appears only once in the final report. When dealing with complex search criteria, such as searching for multiple strings and printing rows after a hit, you might find combining search for multiple strings and printing rows after a hit in grep useful for expanding beyond simple line inclusion.

Performance Considerations for Large Files

While Grep is highly optimized, comparing very large files can still be resource-intensive. The -F flag uses a fast string matching algorithm, making it suitable for files with millions of lines. However, if source.txt is extremely large, consider sorting both files and using the comm command instead, which can be more memory-efficient for set operations. Always test your commands on small subsets of data first. Verify that the pattern file does not contain empty lines, as an empty line in source.txt will match every line in target.txt if not handled correctly. You can filter out empty lines from your pattern file using grep -v '^$' before passing it to Grep.

Frequently Asked Questions

Does grep -f work with regular expressions?

No, when using -f without the -E or -G flags, Grep treats patterns as fixed strings by default. To enable regular expression interpretation for patterns in a file, you must explicitly use the -E flag, though this may significantly reduce performance on large datasets.

How do I handle files with different line endings?

If one file uses Windows-style CRLF endings and the other uses Unix-style LF endings, Grep may fail to match lines due to the invisible carriage return character. You should convert the file endings using dos2unix or sed to ensure consistent formatting before running the comparison.

Can I get the line numbers of the matches?

Yes, adding the -n flag to the Grep command will prefix each output line with its line number in target.txt. This is helpful for debugging or referencing specific locations in large log files where context matters.

What if source.txt has duplicate lines?

Duplicate lines in source.txt do not affect the correctness of the output. Grep will simply check each line in target.txt against the set of patterns. If target.txt contains duplicates, they will appear in the output multiple times unless you pipe the result through sort -u.

Is there a limit to the size of the pattern file?

Grep can handle pattern files limited primarily by available system memory and the maximum number of open file descriptors. For extremely large pattern files, consider splitting them into chunks or using specialized database tools designed for high-volume lookups.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More