I need to identify patterns in a text file for further analysis. So the input files may contain semi-structured text as follows;file1905:john: abc123: john@doe.com: US  920:eric: ericaA: eric007@gmail.com: US  1000: rio: ri0ri0: rio@yahoo.com: IN  file2 nathen <tab> nathen@yman.com <tab> 764323545 <tab> UKthomas <tab> thom@gmail.com <tab> 563363421 <tab> UKian <tab> rt@gmail.com <tab> 3453245472 <tab> SPnumber of words in a line may vary for each document. delimiter also vary but unique for each document. what I want is to count number of words per each line in each document.output would be:for file1 5  5 5 5   for file2 4  4 4 4I want generalize this for any file with any delimiter.  It could be - | : \space+ \tab+. Some files are as follows:| hetro@gmail.com | er34532 |  | rt@gmail.com | 764474 |
BASH: count # of words in each line of a document
bash;patterns
For file2 with its simple format of white-space separated words, try:$ awk '{print NF}' file2444In awk, NF is the number of fields.  In awk by default, words characters separated by white-space.For file1, for which words may be separated by colons or spaces, we need to add : to the field separator:$ awk -F'[: \t]+' '{print NF}' file1555Improvementawk will think there are extra fields if a line has leading or trailing whitespace.  We can fix that by removing any such whitespace before we count the fields, like this for file1:awk -F'[: \t]+' '{gsub(/^[: \t]+|[: \t]+$/, ); print NF}' file1or this for file2:awk '{gsub(/^[[:space:]]+|[[:space:]]+$/, ); print NF}' file2In the regex, ^[[:space:]]+ matches leading whitespace and [[:space:]]+$ matches trailing whitespace.  Their combination in the gsub command removes  both.GeneralizationIf the field separator could be any of - | :  or , then use:awk -F'[-|: \t]+' '{gsub(/^[[-\|: \t]+|[[-\|: \t]+$/, ); print NF}'Example:$ cat file3| hetro@gmail.com | er34532 |  | rt@gmail.com | 764474 |$ awk -F'[-|: \t]+' '{gsub(/^[[-\|: \t]+|[[-\|: \t]+$/, ); print NF}' file322