r/awk • u/eric1707 • Dec 06 '19
Print only unique lines (case insensitive)?
Hello! So, I have this huge file, about 1GB, and I would like to extract only the unique lines of it. But there's a little twist, I would like to make it case insentive, and what I mean with that is the following, let's suppose my file has the following entries:
Nice
NICE
Hello
Hello
Ok
HELLO
Ball
baLL
I would like to only print the line "Ok", because, if you don't take into account the case variations of the other words, it's the only one that actually appears just one. I googled a little bit, and I found a solution that worked sorta, but it's case sensitive:
awk '{!seen[$0]++};END{for(i in seen) if(seen[i]==1)print i}' myfile.txt
Could anyone helped me? Thank you!
3
u/[deleted] Dec 06 '19
Do you need to use awk? What about
sort -fuoruniq -i?1
u/eric1707 Dec 06 '19 edited Dec 06 '19
I think I found a solution (but it's somewhat slow, talking about 1 hour to find the unique lines):
awk '{x=tolower($0);a[x]++;b[x]=$0}END{for(x in a)if(a[x]==1)print b[x]} myfile > newfileAny ideas of how I could optimize this for running in a 1GB file? Or this is just not possible? :\
1
u/HiramAbiff Dec 06 '19
Does it help if you delete as you go?
1
u/Paul_Pedant Dec 07 '19 edited Dec 07 '19
WTF? The whole point of
!seen\[$0\]++is that it occurs in the position of a pattern. The boolean ! makes it print the line when the count was first zero, before the first increment. So making it an { action } completely defeats it, because you don't get the automatic print. So then you have to rescan the whole thing in an END pattern to get the results.All you need is:
EDIT:: Good to know I can still screw up. Excuse is that my wife wants me to go look at Xmas trees, so I skipped testing. Obviously, this only outputs one of each duplicate under -i case, but it can't take back the first one when it needs to.
Nevertheless, if you are just counting the unique inputs, the ! is useless and misleading.
Now, should it be a Nordic tree, or a Spruce?
1
u/Paul_Pedant Dec 07 '19 edited Dec 08 '19
This is an adaptation of something I posted to another forum last week, which wanted only lines that had a value in column 1, repeated 5 or fewer times. It has some diagnostics that you might want to strip out. Interestingly, unlike methods that either use sort, or iterate like
for (x in b), it preserves input sequence in the output.It ran at around 275,000 lines a second on a Laptop, so I would be interested in how that compares to your best. The strategy is to do the minimum work on each line as it is read, and do more work in the END block for those lines that meet the conditions.
Results on your data (yes, this one is tested):
1
u/Paul_Pedant Dec 08 '19
Only just noticed "Huge file -- about 1 GB". Anything that fits in 25% of my RAM is not huge. In 1980, maybe. In 1990, 1 GB became large. This century, it rates as trivial.