Skip to content

Commit 8bac2d8

Browse files
committed
Add Find Duplicate Lines In A File as a Unix TIL
1 parent 629d8b7 commit 8bac2d8

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1302 TILs and counting..._
13+
_1303 TILs and counting..._
1414

1515
---
1616

@@ -1253,6 +1253,7 @@ _1302 TILs and counting..._
12531253
- [File Type Info With File](unix/file-type-info-with-file.md)
12541254
- [Find All Files Matching A Name With fd](unix/find-all-files-matching-a-name-with-fd.md)
12551255
- [Find A File Installed By Brew](unix/find-a-file-installed-by-brew.md)
1256+
- [Find Duplicate Lines In A File](unix/find-duplicate-lines-in-a-file.md)
12561257
- [Find Files With fd](unix/find-files-with-fd.md)
12571258
- [Find Newer Files](unix/find-newer-files.md)
12581259
- [Fix Unlinked Node Binaries With asdf](unix/fix-unlinked-node-binaries-with-asdf.md)
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Find Duplicate Lines In A File
2+
3+
Let's say I have a large file in a Ruby project. I want to find instances of a
4+
`field` declaration being duplicated throughout the file. Just searching for
5+
duplicate lines within the file is going to result in all kinds of false
6+
positives (think, lots of duplicate `end` lines).
7+
8+
What I can do is `grep` for a pattern that will just match on the lines that
9+
are `field` declarations. The results of the `grep` can then be piped to `sort`
10+
which will order them. This ordering will mean that any duplicates are placed
11+
next to each other. Lastly, I'll pipe the sorted lines to `uniq` with the `-d`
12+
flag which will filter the results down to just those lines that are repeated.
13+
14+
Here is what the whole thing looks like:
15+
16+
```
17+
$ grep -o "field :[a-zA-Z_][a-zA-Z_0-9]*" file.rb | sort | uniq -d
18+
```
19+
20+
See `man uniq` for more details on the available flags.

0 commit comments

Comments
 (0)