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
andread -d ""
options protects filenames which contain special characters such as a space character. - The syntax
<(find ..)
is a process substitution and the output offind
is fed to theread
command in thewhile
loop via the redirect.