Artificial intelligent assistant

Count characters in two specific lines in all files and printing the sum with corresponding filename Following is the case: there are multiple *.txt files each containing below lines with different values of `var` or `lab`. For example: `abc.txt`: var^ABCDEFG lab^ABCDEFGH `def.txt`: var^ABCDEFGHI lab^ABCDEFGHIJ I need a command or script which will print sum of number of characters in (`var^` or `lab^`) for each .txt file. Sample output: abc.txt: Total Characters in (Var and Lab) are 15. (counting character after the caret ^ sign) def.txt: Total Characters in (Var and Lab) are 19.

Expanding @steeldriver's answer to other `awk` implementations without `BEGINFILE` and `ENDFILE` makes it a bit messier, but portable:


awk -F'^' 'FNR==1{if (NR>FNR) printf("%s : Total characters in (Var) and (Lab) are %d\
",lastfile,sum); sum=0; lastfile=FILENAME} \
NF==2 && ($1=="var" || $1=="lab") {sum+=length($2)} \
END{printf "%s: Total characters in (Var) and (Lab) are %d\
", FILENAME, sum}' abc.txt def.txt


To explain:

* At beginning of file, (i.e. `FNR`, the per-file-line counter, is 1), we store the filename in a temporary variable `lastfile` and set the counter variable to 0.

* If this is not the first file (i.e. `NR`, the global line-counter, is larger than `FNR`), we output the statistics from the previous file.

* Since this rule would not catch the last file on `awk`'s argument list, we have to replicate the logic also in the global `END` block.

xcX3v84RxoQ-4GxG32940ukFUIEgYdPy e01d58ab18bf93a8f140be9efca97dd8