Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Last active February 13, 2016 07:24
Show Gist options
  • Select an option

  • Save AndrewRayCode/16b8163fe2688677fd88 to your computer and use it in GitHub Desktop.

Select an option

Save AndrewRayCode/16b8163fe2688677fd88 to your computer and use it in GitHub Desktop.
Compare the occurrence / frequency of words used in two files with bash and (g)awk
# Note, on osx, brew install gawk
# Replace FILE1 and FILE2 with your files
# Multi line, commented:
gawk \
# This gawk program lowercases both words and counts how many times they\
# appear in each file\
'FNR == NR\
{ a[tolower($0)]++; next }\
{ b[tolower($0)]++ }\
END\
{ for (i in a) {\
if (i in b) {\
sum = a[i] + b[i];\
print sum, i\
}\
} }'\
# Define the "record separator" (needs gawk) as anything not alphanumeric nor a single quote\
# This way "wouldn't" will be treated as one word, instead of "wouldn" and "t"
RS=$'[^[:alnum:]\']+'\
# Your two files to compare\
FILE1 FILE2\
# Sort the output reverse, ignoring whitespace, and numeric, to sort leading numbers correctly\
| sort -bnr
# Alternatively, on a single line:
gawk 'FNR == NR { a[tolower($0)]++; next } { b[tolower($0)]++ } END { for (i in a) if (i in b) { sum = a[i] + b[i]; print sum, i } }' RS=$'[^[:alnum:]\']+' FILE1 FILE2 | sort -bnr
# Alternatively, place the awk script into its own file
echo 'FNR == NR { a[tolower($0)]++; next } { b[tolower($0)]++ } END { for (i in a) if (i in b) { sum = a[i] + b[i]; print sum, i } }' > gawk_word_count
awk -f gawk_word_count FILE1 FILE2 | sort -bnr
@AndrewRayCode

Copy link
Copy Markdown
Author
gawk 'FNR == NR { a[tolower($0)]++; next } { b[tolower($0)]++ } END { for (i in a) if (i in b) { sum = a[i] + b[i]; printf "%-3s %-20s %s %s %s %s\n", sum, i, "file1:",a[i], "file2:",b[i]; } }' RS=$'[^[:alnum:]\']+' file1 file2 | sort -bnr

@AndrewRayCode

Copy link
Copy Markdown
Author
gawk 'FNR == NR { a[tolower($0)]++; next } { b[tolower($0)]++ } END { for (i in a) if (i in b) { sum = a[i] + b[i]; p1 = ( ( a[i] / length(a) ) * 100 ) "%"; p2 = ( ( b[i] / length(a) ) * 100 ) "%"; printf "%-4s %-20s %s %-10s ( %-4s) %s %-10s ( %-4s)\n", sum, i, "file1:",p1,a[i], "file2:",p2,b[i]; } }' RS=$'[^[:alnum:]\']+' file1 file2 | sort -bnr

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment