Home > OS >  Count no.of .xlsx across all the directories and subdirectories where .tab is also exist
Count no.of .xlsx across all the directories and subdirectories where .tab is also exist

Time:07-11

I have a directroy which consists of 'n' number of sub directories. Following is the structure:

RootDir -> 
SubDir1 ->  
test.xlsx
test.tab 
SubDir2 ->
test.xlsx

As shown above SubDir1 has both files .xlsx and .tab and SubDir2 have only .xlsx. Like this I have 'n' number of subdirectories, and willing to count only .xlsx from the folders where .tab file is also present.

I wanted to do it using shell scripting.

The present code returning me count of .xlsx files. But, it also includes the .xlsx files where .tab fiiles are not present.

find . -name '*.xlsx' -type f

CodePudding user response:

The following code should work:

count=0
for file in `find . -name '*.xlsx' -type f`; do
  if [ -f "${file%.xlsx}"".tab" ]; then
    count=`expr $count   1`
  fi
done
echo $count

CodePudding user response:

A slightly refined version of Ankush Pandit's answer:

#!/bin/bash

count=0
while IFS= read -r -d "" f; do
    [[ -f ${f%.xlsx*}.tab ]] && (( count   ))
done < <(find RootDir -type f -name "*.xlsx" -print0)
echo "$count"
  • The combination of -print0 and read -d "" options protects filenames which contain special characters such as a space character.
  • The syntax <(find ..) is a process substitution and the output of find is fed to the read command in the while loop via the redirect.
  • Related