简体   繁体   中英

Bash - Count how often a line appears

File A is the file I have to search through. File B is the File, that has what I need to search in file A.

File A is a lot of code, simular to this:

test test 
a = rr
b = gg
test test
c = a + b
test 

Those variables are sometimes only declared, and not used, and I filtered all variables, that I need out, into File B:

a
b

I want to count how often each variable (each variable in File B has its own line, and is a string), appears in File B.

I would use count if in Excel to get this going, but I don´t know how to do something simular in Bash.

I tried to use grep -wc File_B File_A But this did not work for me, I guess its because this try´s to find the complete File_B in File_A, but that does not work.

Any help would be apprechiated.

Kind regards

Elias

The command grep -wc File_B File_A actually searches for the word File_B in the file File_A .

What you may have wanted is grep -wcf File_B File_A - the -f means "don't search for the pattern File_B , instead read the patterns to search from File_B .

The thing is, that will count all the matches from File_B that are found in File_A and sum it for you, so if the pattern on the first line of File_B is found 8 times, and the pattern on the second line of File_B is found 4 times, grep -wcf will just print 12. If you want to have an output that lists how many times each pattern was found, you'd want to write a loop that reads each line from File_B and grep s for it individually.

Maybe something like this:

while read pat; do echo -n "$pat: "; grep -wc "$pat" File_A; done < File_B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM