1

I've got several different directories that contain different versions of some files. I want to count a symbol in all versions of the same file. Here is an example of the hierarchy.

directory
    version1
        1_file.txt
        2_file.txt
        ...
    version2
        1_file.txt
        2_file.txt 
        ... 
    ...

I've tried the following:

symbol=\>

for i in 1 2 3; do
    grep -roh $symbol $i\_file.txt | wc -w;
done
  • 1
    add a */ before the $i in the grep and you are done (if your cwd is directory) and you don't need the -r flag. – ikrabbe Jul 9 '15 at 20:11
  • You don't need loop at all: grep -oh "$symbol" */{1..3}_file.txt | wc -w. Also -r switch is redundant, perhaps just grep -roh "$symbol" . | wc -w is sufficient for you. – jimmij Jul 9 '15 at 20:23
  • You also have an extra backslash before file.txt on the grep line – Jeff Schaller Jul 9 '15 at 21:55
  • I believe there's a POSIX "-c" option to grep to print a count of matching lines for each input file. surely that must ..count for something? – Theophrastus Jul 9 '15 at 23:59
1
find . -name \[123]_file.txt -exec cat {} + | tr -sc \> \\n | wc -l

...will work for sequences of your single character example. But if the string is more complex, then is probably a good idea to go with the -only GNU switch to grep. Like:

find . -name \[123]_file.txt -exec grep -o \> {} + | wc -l

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.