0

Say I have the following problem

  • Count the files in the folder which have an "a" in the filename
  • Repeat for "e", "i" and all the other vowels

One solution is:

FilesWithA=$(ls | grep a | wc -l)
FilesWithE=$(ls | grep e | wc -l)
FilesWithI=$(ls | grep i | wc -l)
FilesWithO=$(ls | grep o | wc -l)
FilesWithU=$(ls | grep u | wc -l)

This works fine, but the folder contains many thousands of files. I'm looking to speed this up by capturing the output of ls in a variable, then sending the output to grep and wc, but the syntax is defeating me.

lsCaptured=$(ls)
FilesWithA=$($lsCaptured | grep a | wc -l) #not working!
3

1 Answer 1

2

Use this :

#!/bin/bash

captured="$(printf '%s\n' *)"
filesWithA=$(grep -c a <<< "$captured")

 Notes :

Sign up to request clarification or add additional context in comments.

2 Comments

grep has the -c option for counting -- no need for wc.
Awesome, thanks! Just what I needed. The answers suggested in a comment were not helpful. Note that you can insert the here-string even in more complex commands such as FilesWithA=$(grep a <<< "$captured" | wc -l).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.