Count Frequency of Words in a Text File: ignore 'person', 'file', not count 'personal', 'personnel', 'personally', 'hypersonic', desired results

Abstract: Exclude exact words like person and file from word frequency counts while preserving derivatives such as personal and hypersonic.

Created: 2026-08-28 by
To count word frequencies in a text file while excluding specific terms like 'person' and 'file' but retaining their derivatives such as 'personal', you must use exact whole-word matching rather than substring search. This approach ensures that 'hypersonic' is not mistakenly excluded because it contains 'person'. The most reliable method involves using command-line tools with word boundary anchors or regular expressions that distinguish between complete tokens and partial matches within larger strings.

Understanding Whole-Word Matching

The core challenge lies in the difference between simple string containment and discrete token identification. When you search for the word "person" in a standard text editor or basic script, the engine often finds every occurrence of those five letters in sequence. This means it will match "person", "personal", "personnel", "personally", and even "hypersonic". To solve this, we need to define what constitutes a "word". In computational linguistics and text processing, a word is typically defined as a sequence of characters bounded by whitespace, punctuation, or the start/end of the line. By enforcing these boundaries, we ensure that only the standalone noun "person" is counted. Derivatives like "personal" are treated as distinct lexical items because they have different suffixes attached directly to the root without a separating space. This distinction is critical for accurate frequency analysis, especially when dealing with large corpora where morphological variations are common. Without this precision, your data will be skewed by false positives from compound words or adjectives derived from your target list.

Linux Solution Using grep and awk

On Linux systems, the combination of grep for filtering and awk for counting provides a robust pipeline. The key is using grep -o to extract only the matching parts and then applying word boundary assertions. However, since we want to exclude specific words but include others, we can invert the logic or use negative lookahead if supported, but a simpler approach is to extract all words and filter them. First, normalize the text to lowercase to ensure case-insensitive counting. Then, use grep -oEw to output only whole words. The -w flag automatically handles word boundaries. If you need to exclude "person" and "file" specifically, you can pipe the output through another grep instance that removes lines containing these exact words. Note that grep -w "person" will match "person" but not "personal". Therefore, to get the frequency of other words, you might want to count everything first and then subtract, or simply filter out the unwanted words before counting. Here is a typical one-liner for counting all words except "person" and "file":
cat input.txt | tr '[:upper:]' '[:lower:]' | grep -oEw '[a-z]+' | grep -v '^person$' | grep -v '^file$' | sort | uniq -c | sort -nr
This command converts text to lowercase, extracts individual words, excludes the specified terms, sorts them alphabetically, counts occurrences, and finally sorts by frequency in descending order. This method is efficient and leverages standard Unix utilities available on almost all Linux distributions. For more complex scenarios involving punctuation handling, awk can be used to split fields by non-alphanumeric characters, providing finer control over what is considered a word boundary.

Windows Solution Using PowerShell

Windows users can achieve similar results using PowerShell, which offers powerful object-oriented text processing capabilities. The process involves reading the file, splitting it into words, cleaning up punctuation, and then filtering based on exact string equality. You can use the Select-String cmdlet or simple string manipulation methods. A straightforward approach is to read the content, convert it to lowercase, and use regular expressions to find all word boundaries. The -match operator with \b (word boundary) helps isolate whole words. Once extracted, you can use Where-Object to exclude "person" and "file". Here is an example script:
$content = Get-Content -Path "input.txt" -Raw
$words = $content.ToLower() -split '\W+'
$filteredWords = $words | Where-Object { $_ -ne 'person' -and $_ -ne 'file' -and $_ -ne '' }
$filteredWords | Group-Object | Sort-Object Count -Descending | Select-Object Name, Count
This script reads the entire file into a single string, splits it by non-word characters (whitespace, punctuation), filters out the excluded terms and empty strings resulting from consecutive delimiters, groups the remaining words, and displays the top frequencies. This method is intuitive for Windows administrators familiar with PowerShell syntax and avoids the need for external tools like Perl or Python unless advanced NLP features are required.

Handling Edge Cases and Performance

When processing large files, memory usage becomes a concern. Reading an entire file into memory via -Raw in PowerShell or cat in Linux may cause issues with gigabyte-sized logs. In such cases, streaming approaches are preferred. For Linux, grep processes input line-by-line by default, making it memory-efficient. For PowerShell, using Get-Content without -Raw returns an array of lines, which can be processed in a loop or pipeline to maintain low memory footprint. Another edge case involves hyphenated words. Does "self-person" count as containing "person"? With \b word boundaries, the hyphen is often treated as a separator, so "person" would be matched as a separate word. If you wish to treat hyphens as part of the word, you must adjust your regex pattern accordingly. Additionally, consider locale-specific characters. Accented letters like "é" or "ñ" may not be captured by simple [a-z] patterns. Using Unicode-aware flags or broader character classes like \w (which includes underscores and alphanumeric chars) can help, though \w also includes underscores which may not be desired in all contexts. Always test your patterns against a representative sample of your data to ensure they behave as expected. For related tasks, such as managing permissions for these scripts, see Back: Administrator Privileges Required or Not?. If you need to combine this frequency count with other metadata, refer to Combining Two Formulas: Status Location Condition Met.

Frequently Asked Questions

Does 'grep -w' count 'persons' as 'person'?

No, grep -w matches whole words exactly. It will match "person" but will not match "persons" because the plural suffix makes it a different token. If you need to stem words, you must implement additional logic or use a library that supports natural language processing stemming.

How do I ignore punctuation attached to words?

In Linux, using tr to replace punctuation with spaces before extracting words, or using grep -oEw '[a-zA-Z]+', helps isolate alphabetic words. In PowerShell, splitting by \W+ removes non-word characters, effectively detaching punctuation from the word tokens.

Can I exclude multiple words at once?

Yes, in Linux you can chain multiple grep -v commands or use egrep -v '(person|file)$' to exclude any word matching the alternatives. In PowerShell, you can extend the Where-Object condition with -notin @('person', 'file') for cleaner syntax.

What if my file is very large?

Avoid loading the entire file into memory. Use streaming tools like grep in Linux which process data chunk by chunk. In PowerShell, avoid -Raw and instead iterate through lines or use Get-Content in a pipeline to keep memory usage constant regardless of file size.

How do I handle case sensitivity?

Always normalize the text to lowercase before counting to ensure "Person" and "person" are counted together. Use tr '[:upper:]' '[:lower:]' in Linux or .ToLower() in PowerShell. Ensure your exclusion list is also in lowercase to maintain consistency.

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